The foregoing review
Previous article focuses on the introduction of styles and images react, the need to increase what configuration, This part describes the introduction redux react in the
A brief description
redux The core idea is to maintain a unified state, which solves the problem of communication between the control.
Add Reference
# redux
npm install --save react-redux redux redux-thunk
# redux-logger
npm install --save-dev redux-logger
add files
constants folder Tim actionTypes.js
export const DIV_TOGGLE = 'DIV_TOGGLE'
action folder Add index.js
import * as actionType from '../constants/actionTypes' export const divToggle = () => ({ type: actionType.DIV_TOGGLE })
reducers folder Add index.js
import * as actionType from '../constants/actionTypes' const store = (state = { isShow: false }, action) => { switch (action.type) { case actionType.DIV_TOGGLE: return { ...state, isShow: !state.isShow } default: return state } } export default store
components folder add MyButton.js, MyImage.js
import React from 'react'; import { connect } from 'react-redux'; import { divToggle } from '../action/index' class MyButton extends React.Component { render() { let { divToggle } = this.props return ( <button onClick={divToggle}>切换图片显示</button> ); } } //定义属性 const mapStateToProps = state => { return { } } //定义事件 const mapDispatchToProps = (dispatch, ownProps) => { return { // 订单提交 divToggle: (e) => { dispatch(divToggle()) } } } export default connect(mapStateToProps, mapDispatchToProps)(MyButton)
import React from 'react'; import { connect } from 'react-redux'; import img from '../styles/images/bg.png' class MyImage extends React.Component { render() { let { state } = this.props return ( <img src={img} style={{ display: state.isShow ? '' : 'none' }} /> ); } } //定义属性 const mapStateToProps = state => { return { state } } export default connect(mapStateToProps)(MyImage)
pages folder Add home.js
import React from 'react'; import MyImage from '../components/MyImage' import MyButton from '../components/MyButton' class Home extends React.Component { render() { return ( <div> <MyButton></MyButton> <div> <MyImage /> </div> </div> ); } } export default Home
Modify index.js
import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import { createLogger } from 'redux-logger' import thunk from 'redux-thunk' import reducer from './reducers/index' import Home from './pages/home' const middleware = [ thunk ]; if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()); } const store = createStore( reducer, applyMiddleware(...middleware) ) render( <Provider store={store}> <Home /> </Provider>, document.getElementById('root') )