react状态管理
redux的执行机制
安装npm包
npm i -S react-redux redux redux-thunk
配置redux
./store/index
import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer/index';
const middleware = [ thunk ];
export const store = createStore(reducer, {},applyMiddleware(...middleware))
./reducer/index.js
import { combineReducers } from 'redux'
import item from './item'
export default combineReducers({
reducer:item
})
./item.js
import { Add ,Post } from "../Type";
const states = {
pageTitle:686,
infoList:68998
}
export default function (state =states,action) {
switch (action.type) {
case Add:
return {
...state,
pageTitle:action.data
}
case Post:
return {
...state,
infoList:action.data
}
default:
return state;
}
}
…/Type.js
export const Add = "Add"
export const Post = "Post"
…/…/store/action.js
import { Add ,Post } from "../Type";
export const add = (data) =>{
return ( dispatch ) =>{
console.log(data-1)
dispatch({
type:Add,
data:data + 99
})
}
}
export const post = (data) =>{
return ( dispatch ) =>{
console.log(data)
dispatch({
type:Post,
data:data -100
})
}
}
应用redux
app.js
import React, {Component} from 'react';
import { store } from "./store/index";
import { Provider } from 'react-redux';
import Book from './components/Book/Book'
class App extends Component {
constructor(props) {
super(props);
this.state={ }
}
render(){
return (
<Provider store={store}>
<div className="App">
<Book h={{hu:'6666666666'}} />
</div>
</Provider>
);
}
}
export default App;
Book.js
import React, {Component} from 'react';
import { add } from "../../store/action";
import { connect } from 'react-redux';
class Book extends Component {
componentDidMount(){
this.props.add(888);
}
render() {
console.log(this.props)
return (
<div>
{ this.props.pageTitle }
</div>
);
}
}
const mapStateToProps = state => {
return {
pageTitle:state.reducer.pageTitle,
infoList:state.reducer.infoList
}
}
export default connect(mapStateToProps, { add })(Book);
return {
pageTitle:state.reducer.pageTitle,
infoList:state.reducer.infoList
}
}
export default connect(mapStateToProps, { add })(Book);
|