react-redux1

安装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做连接

 

posted @ 2020-07-12 00:11  雪糕战士  阅读(116)  评论(0编辑  收藏  举报