大致需要的步骤 下载 创建store actions(动作获取数据) actionsType (常量定义) reducers (改变state)
总结过程 自言自语 当点击按钮获取数据时 触发action中函数,拿到数据 给到reducers 来改变 state 中间需要一系列的处理。 需要将组件 包围在Provider 标签中(一般将项目app 标签包围)才可以将 store 传给所有组件。
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
需要将组件与redux连接 connect ([mapStateToProps], [mapDispatchToProps])(component)
Connect | React Redux 中文文档 (react-redux.js.org) 文档
在触发action中函数后拿到数据 需要 dispatch(function(data));
export const function= (obj) =>{
return{
type:常量 NAME,
obj
}
}
之后在reducers 中根据常量名字 判断执行哪个
switch(action.type){
case MEETING_SUMMARY_SET_DETAILS:
return {
...state,
summaryDetails:action.obj
}
case MEETING_SUMMARY_SET_DETAILS_COMMENT:
return {
...state,
summaryDetails_comment:action.obj
}
default:
return state
}
1、下载依赖 npm
2、创建store.js 不能完全复制 只是例子 大致是这些代码
import { createStore, applyMiddleware, combineReducers, compose } from 'redux'
import reducers from './reducers'
import thunk from 'redux-thunk'
const rootReducer = combineReducers(reducers);
const configureStore = (initialState) => {
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
return store;
}
const store = configureStore()
export default store
3、创建文件夹 actions 进行获取数据 处理数据一系列操作
import import * as actions from 'actionsType ' // 对应的文件
export const addonefun= (num) =>{ //最好是定义一个函数 return出去一个带有type 的对象
//因为reducers 需要用type 判断
return{
type:ADD,
num :1
}
}
export const squarefun = (num) =>{
return{
type:ADD,
num :1
}
}
const addone = (num)=> {
//进行操作 可以是ajsx 之类的
console.log(num)
dispatch(addonefun(num))
}
const square = (num)=> {
//进行操作 可以是ajsx 之类的
console.log(num)
dispatch(squarefun (num)) //也可以不定义函数 直接将return
// {type:ADD,num :1}
}
export{
addone,
square
}
4、创建actionsType index.js 用于定义常量
const ADD = 'ADD'
const SQUARE = 'SQUARE '
export{
ADD,
SQUARE
}
5、创建reducers 用于更新state
import * as actions from '../../../actionsType/'
const math = (state = 10,action) =>{
switch(action.type){
case ADD:
return state + action.num
case SQUARE :
return state * state
default:
return state
}
}
export default math
6、组件中调用 大致是这样的
import React, { Component } from 'react'
import * from '../action'
import { Connect } from 'react-redux'
class xx extends Component {
render() {
return (
<div>
<button onClick={()=>{addone(1)}}></button>
<button onClick={()=>{square(2)}}></button>
</div>
)
}
}
const mapStateToProps = (state)=>({
math:state
})
const mapDispatchToProps = (dispatch) => ({
addone(params){
dispatch(addone(params))//这个是action中的
},
square(params) {
dispatch(square(params))
}
})
export default connect(mapStateToProps, mapDispatchToProps)(xx);