安装redux
npm install --save redux react-redux
react-redux帮助你完成数据订阅
使用redux--同步
actions-type.js:
//定义常量:
export const ADDCOMMENTS = 'addComments'
export const DELCOMMENTS = 'delComments'
export const INITCOMMENTS = 'initComments'
actions.js:
//在actions.js中完成数据的获取与处理的工作
import { ADDCOMMENTS, DELCOMMENTS, INITCOMMENTS } from './actions-type'
export const addComments = comment => ({ type: ADDCOMMENTS, data: comment })
export const delComments = index => ({ type: DELCOMMENTS, data: index })
}
reducers.js:
import {ADDCOMMENTS,DELCOMMENTS,INITCOMMENTS} from './actions-type'
const comments = [
{
name:'Tom',comment:'React不错'
},
{
name:'Tony',comment:'React不错,不过javascript基础很重要'
}
]
export function comment(state=comments,action){
switch(action.type){
case ADDCOMMENTS:
return [action.data,...state]
case DELCOMMENTS:
return state.filter( (item,index)=>{
return index !== action.data
})
case INITCOMMENTS:
return action.data
default:
return state
}
}
store.js:
import {createStore} from 'redux'
import {comment} from './reducers'
const state = createStore(comment)
export default state
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')
);
app.jsx:
// 在原有class类的基础上加上下面的代码
import {addComments,delComments} from '../../redux/actions'
import {connect} from 'react-redux'
export default connect(
state => ({comments: state}),
{addComments,delComments}
)(App)
redux--异步
其他内容不变,改变store.js和actions.js store.js:
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import {comment} from './reducers'
import {composeWithDevTools } from 'redux-devtools-extension'
const state = createStore(comment,
composeWithDevTools( applyMiddleware(thunk))
)
export default state
actions.js:
import { ADDCOMMENTS, DELCOMMENTS, INITCOMMENTS } from './actions-type'
export const addComments = comment => ({ type: ADDCOMMENTS, data: comment })
export const delComments = index => ({ type: DELCOMMENTS, data: index })
const initcomments = (comments) => ({ type: INITCOMMENTS, data: comments })
export const initcomment = () => {
return dispatch => {
setTimeout(() => {
const comments = [
{
name: 'Tom', comment: 'React不错'
},
{
name: 'Tony', comment: 'React不错,不过javascript基础很重要'
}
]
dispatch(initcomments(comments))
}, 1000)
}
}