React-Redux(一):react-redux使用
2021-01-07 本文已影响0人
Viewwei
- react-redux使用步骤如下
- 添加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;
- 在祖先元素引入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
- 使用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一样使用中间件