码迷,mamicode.com
首页 > 其他好文 > 详细

react-redux1

时间:2020-07-12 01:17:07      阅读:80      评论:0      收藏:0      [点我收藏+]

标签: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做连接

 

react-redux1

标签:span   code   hang   red   rom   export   形式   defaults   传值   

原文地址:https://www.cnblogs.com/nothingness/p/13286262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!