歆萌 2020-01-08
1.首先命令安装 npm install redux react-redux --save
2.在项目中找到index.js
插入代码
import React from ‘react‘; import ReactDOM from ‘react-dom‘; import App from "./App" import ‘./index.css‘; import * as serviceWorker from ‘./serviceWorker‘; import { Provider } from "react-redux" import { createStore } from ‘redux‘ import rootReducer from ‘./reducers‘ // import Home from "./components/Home" const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) ReactDOM.render( <Provider store={store}> <div> <App/> </div> </Provider>, document.getElementById("root") ) serviceWorker.unregister();
2.查看app.js
import React from ‘react‘; import ‘./App.css‘; import Home from "./components/Home" function App() { return ( <div className="App"> <Home></Home> </div> ); } export default App;
3.在src里面创建actions和reducers文件夹
4.actions文件夹下面创建2个index.js与counter.jsx文件
5.actions里面的index.jsx文件代码如下
import * as counterCreator from ‘./counter‘ export { counterCreator }
6.actions里面的counter.jsx文件代码如下
export function increment(){ return { type:‘INCREMENT‘ } 5 }
7.reducers里面的index.jsx文件代码如下
import {combineReducers} from "redux" import counter from ‘./counter‘ export default combineReducers({ counter, })
8.reducers里面的counter.jsx代码如下
const initialState = { num:0 } //state export default (state = initialState,action) => { switch (action.type){ case ‘INCREMENT‘: return { ...state, num:state.num+1 } default: return state } }
9.最后我们的主页代码
import React, { Component } from ‘react‘ import { connect } from ‘react-redux‘ import { counterCreator } from ‘../actions‘ class Home extends Component { constructor(props){ super(props) this.state = { } } btn = () => { this.props.increment() } render() { return ( <div> {this.props.$$counter} <button onClick={this.btn}>触发</button> </div> ) } } const mapStateToProps = (state) => { return { $$counter: state.counter.num } } const mapDispatchToProps = (dispatch) => ({ increment: () => dispatch(counterCreator.increment()) }) export default connect( mapStateToProps, mapDispatchToProps )(Home)