1.声明action常量
export const INCREASE = 'INCREASE'
export const GETSUCCESS = 'GETSUCCESS'
2.初始化state数据
const initialState = {
number: 1,
lists: [
{
text: 'ww整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中。'
},
],
data: []
}
3.通过dispatch action进入
export
default
function update(state = initialState, action) {
// 根据不同的action type进行state的更新
switch (action.type) {
case INCREASE:
return Object.assign({}, state, {
number: state.number + action.amount
})
break
case GETSUCCESS:
return Object.assign({}, state, {
data: action.json
})
default:
return state
}
}
4.返回一个action对象
export const increase = n = > {
return {
type: INCREASE,
amount: n
}
}
export const getSuccess = (json) = > {
return {
type: GETSUCCESS,
json
}
}
function fetchPosts() {
return dispatch = > {
return fetch('data.json')
.then((res) = > {
console.log(res.status);
return res.json()
})
.then((data) = > {
dispatch(getSuccess(data))
})
.
catch ((e) = > {
console.log(e.message)
})
}
}
// 这里的方法返回一个函数进行异步操作
export
function fetchPostsIfNeeded() {
// 注意这个函数也接收了 getState() 方法
// 它让你选择接下来 dispatch 什么
return (dispatch, getState) = > {
return dispatch(fetchPosts())
}
}
5.方法
const getList = state = > {
return {
lists: state.update.data//通过this.props.lists获取到页面:更新到state的lists里的
}
}
export
default connect(
getList, {
fetchPostsIfNeeded, refreshData//需要条用的state里的方法 增加/删除 通过this.props.—— 用
})(Bar)
6.
render( < Provider store = {
store
} > < div > < Router history = {
history
}
routes = {
routes
}
/>
<DevTools / > < /div>
</Provider > ,
document.getElementById('mount'))