react 框架有自己的一些语法,如 jsx, 组件化。但是组件之间的数据传递,会成为一大难题。所以就不得不使用一个数据驱动的框架, 那就是
redux
1. 创建 store
大多数情况下,会在 /src
目录下创建一个 store
的文件夹,来管理 redux
相关。
先上图:
所以,首先得有一个store
, 那么在 /src/store
文件夹下创建 index.js
/src/store/index.js
// 引入需要用到的方法
import { createStore, compose, applyMiddleware } from 'redux'
// 引入 reducer
import reducer from './reducer'
// 引入 redux 中间件 thunk : 目的为了可以使action 返回一个 函数方法。
// 使用redux的chrome插件, 以及为了使用 redux 的 中间件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// 创建 store
const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
))
// 导出 store
export default store
2.创建 reducer
store
实际上是无法操作 数据state
, 它只能将action
发送给reducer
,根据reducer
返回新得newState
来替换以前得数据state
。(记住,不允许直接更改state
)
/src/store/reducer.js
// 创建 默认的 state
const defaultState = {
something: ''
}
// 创建 reducer reducer默认是一个函数,接受两个参数,分别是 state 和 action
// state 是 原始的state, 而 action ,如果用户提交 dispatch, 那么这里就会接收到
const reducer = (state, action) => {
// action 会有一个 type 属性,还可能会伴随着 其他需要的自定义属性
if (action.type === ??) {
// 深拷贝
const newState = JSON.parse(JSON.stringify(state))
// 赋值 用户传输过来的 data
newState.something = action.data
// 返回新的state "newState"
return newState
}
return state
}
3.创建 actionTypes 和 创建 actionCreators
因为随着越来越多的数据需要管理,我们不应该直接在组件的业务逻辑里,直接手写
action.type
,容易出现拼写错误,但是不会报错,而且直接dispatch
手写的action
会很难去维护,所以需要创建actionTypes
和actionCreators
。
/src/store/actionTypes.js
export const CHNAGE_SEARCH_LIST = 'change_search_list'
export const LOGIN = 'login'
/src/store/actionCreators.js
import * as actionTypes from './actionTypes'
// 假设有这样的一些action
const searchList = (data) => ({
type: actionTypes.CHANGE_SEARCH_LIST,
data
})
const userLogin = (data) => ({
type: actionTypes.LOGIN,
data
})
// 引入 store
import store from './store'
// 引入 action 生成器
import { searchList, userLogin } from './store/actionCreators.js'
render() {
return (<div>...</div>)
}
// 寻找方法
handleClickSearchBtn(data) {
// dispatch 这个 生成的action
store.dispatch(searchList(data))
}
// 登录逻辑方法
handleLogin(data) {
// dispatch 生成的action
store.dispatch(userLogin(data))
}
以上~