redux、react-redux、react-thunk 基本用法记录

开发脚手架: create-react-app
环境:

image

写了个demo,总共三个文件。app.js页面组件、index.js入口文件、redux.js存放reducers和store,当然action也可以抽离出来,我写在了app里,下面是代码:

index.js入口:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reducer from './redux';
import thunk from 'redux-thunk';
//创建store

const store = createStore(reducer, applyMiddleware(thunk));

ReactDOM.render(
    
        
    ,
    document.getElementById('root')
);

app.js组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';

// 异步 ACTION  示例
const delayAdd = () => (dispatch, getState) => {
  setTimeout(() => {
    dispatch({ type: 'add' });
  }, 1000);
}

class App extends Component {
  componentDidMount() {
    console.log(this.props)
  }

  render() {
    const { add, minus, dela } = this.props;
    return (
      

{this.props.person.name}的年龄为{this.props.person.age}

); } } // 需要渲染的state数据 function mapStateToProps(state) { return { person: state } } // 修改state的reducers function mapDispatchToProps(dispatch) { return { add: () => dispatch({ type: 'add' }), minus: () => dispatch({ type: 'minus' }), dela: () => dispatch(delayAdd()) } } export default App = connect(mapStateToProps, mapDispatchToProps)(App)

redux.js:

// store 数据
const person = {
    name: 'nick',
    age: 18
}

//这是同步action  demo
// const increase = {
//    type: 'add'
// }
// const decrease = {
//    type: 'minus'
// }

//这是reducer
const reducer = (state = person, action) => {
    switch (action.type) {
        case 'add':
        // 返回新的 state tree
            return Object.assign({}, state, state.age += 1);
        case 'minus':
            return Object.assign({}, state, state.age -= 1);
        default:
            return state;
    }
}

export default reducer

详情 见GitHub: yizeruier1

你可能感兴趣的:(redux、react-redux、react-thunk 基本用法记录)