美文网首页
React-Redux(一):react-redux使用

React-Redux(一):react-redux使用

作者: Viewwei | 来源:发表于2021-01-07 18:57 被阅读0次
    • react-redux使用步骤如下
      1. 添加react-redux库
    yarn add react-redux
    

    2.创建store

    import {createStore, combineReducers} from "redux";
    
    // 定义修改规则
     const countReducer = (state = 0, action) => {
      switch (action.type) {
        case "ADD":
          return state + 111;
        case "MINUS":
          return state - 1;
        default:
          return state;
      }
    };
    
    const store = createStore(combineReducers({count: countReducer}));
    
    export default store;
    
    1. 在祖先元素引入provider
    import React from 'react';
    import {Provider} from "react-redux";
    import store from '../reactRedux/store'
    import  Children from '../reactRedux/children'
    import  {Provide} from '../reactRedux/inde'
    let ReactRedux = () =>{
        return <div>
            <Provider store={store}>
                <Children/>
            </Provider>
        </div>
    }
    export default ReactRedux
    
    1. 使用react-redux
    import React, { useState } from 'react';
     import {useDispatch,useSelector} from 'react-redux';
    let Children =() =>{
        let countValue = useSelector(state=>state)
        let dispatch = useDispatch()
        // const [count,setCount] = useState(count1.count)
        const add = () =>{
            dispatch()
        }
        return <div>
            <p>{countValue.count}</p>
            <button onClick={e=>add()}>添加</button>
        </div>
    }
    export default Children
    
    • 注意 react-redux dispatch的时候,只能是基本类型,如果需要使用函数,promise ...需要向redux一样使用中间件

    相关文章

      网友评论

          本文标题:React-Redux(一):react-redux使用

          本文链接:https://www.haomeiwen.com/subject/cliooktx.html