redux
一个独立专门用于做状态管理的JS库
作用: 集中式管理react应用中多个组件共享的状态
基础概念参考阮一峰的文档
传送门:
教程一:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
教程二:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
教程三:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
评论管理demo
components 文件夹里放UI组件
containers 文件夹里放容器组件
redux的文件单独放一个文件夹
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './containers/app/app'
import {
Provider} from 'react-redux'
import store from './redux/store'
ReactDOM.render(
<Provider store = {
store}>
<App />
</Provider>
, document.getElementById('root'))
/redux/action-types.js
// 包含所有action type的常量字符
export const ADD_COMMENT = 'add_comment'
export const DELETE_COMMENT = 'delete_comment'
export const RECEIVE_COMMENTS = 'receive_comments'
/redux/actions.js
//包含了所有的action creator----(action的工厂函数)
import {
ADD_COMMENT,DELETE_COMMENT,RECEIVE_COMMENTS} from './action-types'
export const addComment = (comment) => ({
type: ADD_COMMENT, data: comment})
export const deleteComment = (index) => ({
type: DELETE_COMMENT, data: index})
export const receiveComments = (comments) => ({
type: RECEIVE_COMMENTS, data: comments})
// 异步从后台获取数据
export const getComments = () => {
return dispatch => {
//模拟发送ajax请求异步获取数据
setTimeout(() => {
const comments = [
{
username: 'Tom', content: 'React挺好的!'},
{
username: 'Jack', content: 'React好难!'},
]
// 分发一个同步的action
dispatch(receiveComments(comments))
},1000)
}
}
/redux/reducers.js
// 包含n个reducer函数的模块
import {
ADD_COMMENT,DELETE_COMMENT,RECEIVE_COMMENTS} from './action-types'
const initComments = []
export function comments