react-redux的 Provider

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pansuyong/article/details/82927572

index.js配置

import React from 'react';
import ReactDOM from 'react-dom';
//all in js
import './index.css';
// import App from './App';
import TodoList3 from './TodoList3';
// PWA progressive web application
import registerServiceWorker from './registerServiceWorker';

import { Provider} from 'react-redux'
import store from './store/index'
const App=(
    // Provider这个提供器连接了store,那么Provider里面的所有的组件都有能力获取store里面的内容了
    <Provider store={store}>
        <TodoList3 />
    </Provider>

)

// jsx语法(在js文件中直接写html就是用了jsx语法)
//在jsx中绑定变量需要给变量加大括号
// 组件必须以大写开头 <App />
ReactDOM.render(App, document.getElementById('root'));
registerServiceWorker();

Todolist3.js中做连接

import React,{Component} from 'react'
// import store from './store/index'
import {getChangeInputAction,getAddItemAction,getDeleteItemAction} from './store/actionCreators'
import {connect} from 'react-redux'

const TodoList3=(props)=>{
    const {inputValue,changeInputValue,handleClick,list,handleDelete}=props;

    return(
        <div>
            <input
                value={inputValue}
                onChange={changeInputValue}
            />
            <button onClick={handleClick}>提交</button>
            <ul>
                {list.map((item,index)=>{
                return  <li onClick={handleDelete}>{item}</li>
                })}
                {/*{this.getListItem()}*/}

            </ul>
        </div>
    )
};


// 连接方式
/**
 *
 * @param state[store里面的state]
 * @returns {{}}
 */
const mapStateToProps = (state)=>{
    return {
        /**
         * store里面inputValue会映射到组件的props中
         */
        inputValue:state.inputValue,
        list:state.list
    }
}

/**
 *将store.dispatch方法挂载到组件的props上
 * @param dispatch
 */

const mapDispatchToProps=(dispatch)=>{
    return{

//changeInputValue可以用 this.props.changeInputValue()来调用
        changeInputValue(e){
            const action=getChangeInputAction(e.target.value);
            dispatch(action)
        },
        handleClick(){
            const action=getAddItemAction();
            dispatch(action);
        },
        handleDelete(index){
         const action=getDeleteItemAction(index)
            dispatch(action);
        }
    }

}
//让TodoList3与stroe做连接
export default connect(mapStateToProps,mapDispatchToProps)(TodoList3)

猜你喜欢

转载自blog.csdn.net/pansuyong/article/details/82927572