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

2021-01-07  本文已影响0人  Viewwei
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
上一篇下一篇

猜你喜欢

热点阅读