React

React(mapDispatchToProps与mapStat

2017-10-28  本文已影响102人  余生筑

mapDispatchToProps和mapStateToProps 用于维护组件与Store间状态的同步

mapDispatchToProps

const mapDispatchToProps = (dispatch) => {
  alert('Dispatch')
  return {
    onToggleTodo: (id) => {
      dispatch(toggleTodo(id));
    },
    onRemoveTodo: (id) => {
      dispatch(removeTodo(id));
    }
  };
};

父组件

return (<chil
           name='123'
           />)

子组件

return (
<button onClick={onRemove}>删除</button>
<button onClick={onToggle}>切换</button>)
......
......
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
   onToggle:()=>{alert(ownProps.name+'被切换了')},
   onRemove:()=>{alert(ownProps.name+'被删除了')}
  };
};
return (
<button onClick={onRemove}>删除</button>
<button onClick={onToggle}>切换</button>)
.......
const mapDispatchToProps = () => {
  return {
   onToggle:()=>{alert('被切换了')},
   onRemove:()=>{alert('被删除了')}
  };
};

mapStateToProps

上一篇下一篇

猜你喜欢

热点阅读