react 框架有本身的一些语法,如 jsx, 组件化。可是组件之间的数据传递,会成为一大难题。因此就不得不使用一个数据驱动的框架, 那就是
redux
javascript
大多数状况下,会在 /src
目录下建立一个 store
的文件夹,来管理 redux
相关。
先上图:java
因此,首先得有一个store
, 那么在 /src/store
文件夹下建立 index.js
react
/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
复制代码
store
其实是没法操做 数据state
, 它只能将action
发送给reducer
,根据reducer
返回新得newState
来替换之前得数据state
。(记住,不容许直接更改state
)chrome
/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
}
复制代码
由于随着愈来愈多的数据须要管理,咱们不该该直接在组件的业务逻辑里,直接手写
action.type
,容易出现拼写错误,可是不会报错,并且直接dispatch
手写的action
会很难去维护,因此须要建立actionTypes
和actionCreators
。redux
/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))
}
复制代码
以上~app