标签:span code hang red rom export 形式 defaults 传值
安装react-redux
cnpm i react-redux
文件目录
定义store文件
1 index.js文件: 2 3 import { createStore } from ‘redux‘; 4 import reducer from ‘./reducer‘; 5 const store = createStore(reducer); 6 export default store; 7 8 reducer.js文件: 9 10 const defaultState = { 11 inputValue:‘hello‘, 12 list:[] 13 } 14 export default (state=defaultState, action)=>{ 15 if(action.type === ‘change_input_value‘){ 16 const newState = JSON.parse(JSON.stringify(state)); 17 newState.inputValue = action.value; 18 return newState; 19 } 20 return state; 21 }
定义index.js组件渲染部分文件
1 import React from ‘react‘; 2 import ReactDOM from ‘react-dom‘; 3 import TodoList from ‘./TodoList‘; 4 import { Provider } from ‘react-redux‘; 5 import store from ‘./store‘ 6 7 //定义一个APP组件,将store赋值给store, 8 //Provider可以让全局都可以获得store中的值 9 const App = ( 10 <Provider store={store}> 11 <TodoList /> 12 </Provider> 13 ) 14 15 ReactDOM.render(App, document.getElementById(‘root‘));
定义TodoList组件文件
import React, {Component,Fragment} from ‘react‘; import {connect} from ‘react-redux‘; //this.props.inputValue通过组件传值形式来绑定方法 class TodoList extends Component{ render() { return ( <Fragment> <div> <input type="text" value={this.props.inputValue} onChange={this.props.handleInputValue}/> <button>提交按钮</button> </div> <ul> <li>列表一</li> </ul> </Fragment> ) } } const mapStateToProps = (state) => { return { inputValue: state.inputValue } } //mapStateToProps 定义连接规则 const mapDispatchToProps = (dispatch) => { return { handleInputValue: (e) => { const action={ type:‘change_input_value‘, value:e.target.value } dispatch(action) } } } export default connect(mapStateToProps,mapDispatchToProps)(TodoList); //connect,把组件和state做连接
标签:span code hang red rom export 形式 defaults 传值
原文地址:https://www.cnblogs.com/nothingness/p/13286262.html