在React中簡單應用Redux
阿新 • • 發佈:2019-01-06
引入Redux就是為了方便管理狀態,那麼在React程式碼中如何使用了。
換句話說就是如何使用storea裡面維護的state,然後在react中如何產生action,用於更新state。
我們需要用的一個connect函式。
具體看程式碼
import React from "react"; import ReactDOM from "react-dom"; import { createStore, combineReducers, bindActionCreators } from "redux"; import { Provider, connect } from "react-redux"; import "./styles.css"; const initState = { count: 0 }; //預設初始狀態 const counter = (state = initState, action) => { switch (action.type) { case "add": // + 1 return { count: state.count + 1 }; case "sub": // - 1 return { count: state.count - 1 }; case "addAny": // + action.num return { count: state.count + action.num }; default: break; } return state; }; const store = createStore(counter); //生成store function addOne() { //action產生函式 返回一個add action return { type: "add" }; } function subOne() { // 返回一個sub action return { type: "sub" }; } function subAnyCount(cnt) { // 返回一個add cnt action return { type: "addAny", num: cnt }; } class Counter extends React.Component { constructor(props) { super(props); } render() { const { count, addOne, subOne } = this.props; //接受到的三個引數, return ( <div> <button onClick={subOne}>-</button> <span> {count}</span> <button onClick={addOne}>+</button> </div> ); } } //定義了一個函式,用於返回我需要的state.count function mapStatesToProps(state) { return { count: state.count }; } //因為action都需要dispatch, function mapdispatchToProps(dispatch) { return bindActionCreators({ addOne, subOne }, dispatch); } //這是關鍵,Counter就會接受到三個引數 const ConnectCounter = connect( mapStatesToProps, mapdispatchToProps )(Counter); const html = ( <Provider store={store}> <ConnectCounter /> </Provider> ); ReactDOM.render(html, document.getElementById("root"));
效果如圖,點選+,則+1,點選-,則-1