react-redux
npm install react-redux --save
npm install prop-types --save
index.js
import { Provider } from "react-redux"
reactDOM.render((
<Provider store={store}>
<App />
</Provider>
))
app.js
import PropTypes from 'props-types'
import {connect} from 'react-redux'
static propTypes = {
count:PropTypes.number.isRequired,
increment:PropTypes.func.isRequired,
decrement:PropTypes.func.isRequired
}
increment = ()=>{
const number = 10;
this.props.increment(number);
}
render(){
const {count} = this.props.count;
return ()
}
导入改为:
export default connect(
state =>({count:state}),
{increment,decrment}
)(App)
例子2
class useOtherstate extends React.Component{
static propTypes = {
todos:PropTypes.array.isRequired,
addTodo:PropTypes.func.isRequired,
addTodoAsync:PropTypes.func.isRequired
}
this.props.addTodo('Learn about2 js');
this.props.addTodoAsync('Learn jsjjs js');
export default connect(
(state)=>({todos:state}),
{addTodo,addTodoAsync}
)(useOtherstate);
redux默认不支持异步处理
redux-thunk这个依赖包可以解决
npm install --save redux-thunk
store.js
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
const store = createStore(
counter,
applyMiddleware(thunk)
)
export default store;
actions.js
同步返回的都是对象
异步返回的都是一个函数
export const incrementAsync = (number)=>{
return dispatch =>{
setTimeout(
dispatch(increment(number))
,1000)
}
}
另外一个例子
index.js
import thunk from 'redux-thunk'
let store = createStore(
reduce,applyMiddleware(thunk,logger)
);
actions.js
export function addTodo(text) {
return { type: ADD_TODO, text }
}
export function addTodoAsync(text){
return dispatch =>{
setTimeout(()=>{
dispatch(addTodo(text));//注意是作为参数传进去的
},1000)
}
}
添加redux调试工具
在Google插件中搜索redux Devtool
使用下面的配置,要不然找不到store
https://github.com/zalmoxisus/redux-devtools-extension#usage
import { createStore, applyMiddleware, compose } from 'redux';
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+ const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
- const store = createStore(reducer, /* preloadedState, */ compose(
applyMiddleware(...middleware)
));
注意重启本地服务!!!