再見二丁目 | yitimo的个人博客

再见二丁目

react+redux笔记

发布于: 2019-04-02 16:12

此文章久未修订,请自行甄别内容准确性。



至此可以这么使用react+redux:

const store = createStore(...)

class App extends Component{

  componentWillMount(){
    store.subscribe((state)=>this.setState(state))
  }
  
  render(){
    return <Comp state={this.state}
        onIncrease={()=>store.dispatch({type: 'ACTION1'})}
        onDecrease={()=>store.dispatch({type: 'ACTION2'})}
    />
  }
}




至此可以这么使用react+redux+react-redux

const mapStateToProps = (state) => ({
  count: state.count,
})
const mapDispatchToProps = (dispatch, ownProps) => {
  return bindActionCreators({
    increase: action.increase,
    decrease: action.decrease,
  });
}

class MyComp extends Component {
  render(){
    const {count, increase, decrease} = this.props;
    return (<div>
      <div>计数{this.props.count}</div>
      <button onClick={increase}>增加</button>
      <button onClick={decrease}>减少</button>
    </div>)
  }
}

const Comp = connect(mapStateToProps, mapDispatchToProps)(MyComp);


connect后续两个参数之后再深究,其中第三个可以自定义状态如何merge到组件的props中。


参考链接:



  1. 组件dispatch一个ActionA
  2. saga监听到ActionA
  3. 执行异步逻辑
  4. put一个ActionB到reducer
  5. reducer返回新状态到组件