ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[toc] ### 引入store ``` import {createStore, applyMiddleware} from 'redux' import reducer from './reducer' import thunk from 'redux-thunk' // 引入后 action 可以 return 一个方法,否则只能是对象 import { createLogger } from 'redux-logger' // 查看 store const store = createStore( reducer, applyMiddleware(thunk, createLogger()), ); // 创建数据仓库 store.getState() // 获取 state 值 store.dispatch(action) // 直接dispatch action export default store; ``` ### action action的两种写法,引入中间件 thunk前,返回一个对象, store.dispatch(action) ``` export const getInputChangeAction = (value) => ({ type: CHANGE_INPUT_VALUE, value }) const action = getInputChangeAction(e.target.value) store.dispatch(action) ``` 引入 thunk 后,可以返回一个方法,thunk相当于给 dispatch 做了升级 ``` const action = getTodoList() store.dispatch(action) // 直接执行,action 中的方法,其中方法中默认有一个dispatch,用来传递给 action export const getTodoList = () => { return (dispatch) => { axios.get('http://127.0.0.1:3001/test').then(res => { const action = initListAction(res.data) dispatch(action) }) } } export const initListAction = (data) => ({ type: INIT_LIST_ACTION, data }) ``` ### reducer ``` if (action.type === ADD_TODO_ITEM) { const newState = JSON.parse(JSON.stringify(state)) newState.list.push(newState.inputValue) newState.inputValue = ''; return newState } ```