其他分享
首页 > 其他分享> > React(dispatch与参数传递)

React(dispatch与参数传递)

作者:互联网

onClick={fn};

onClick={()=>{fn()}};
//onClick={()=>{fn(id)}};
onClick={fn(id)};
onClick={()=>{fn()}};

等效于

onClick={fn};

TodoList

 todos.map((item) => ( 
        <TodoItem      
          ......
          onToggle={() => onToggleTodo(item.id)}
          onRemove={() => onRemoveTodo(item.id)}
        />
        ))
......
const mapDispatchToProps = (dispatch) => {
  return {
    onToggleTodo: (id) => {
      dispatch(toggleTodo(id));
    },
    onRemoveTodo: (id) => {
      dispatch(removeTodo(id));
    }
  };
};

TodoItem

<input ... onClick={() => {onToggle()}} />
 <button ... onClick={()=>{onRemove()}}>×</button>
//这么写很蠢

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>
......
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
   onToggle:()=>{
    ownProps.onToggle();
  },
   onRemove:()=>{
    ownProps.onRemove();
  } 
  };
};
 todos.map((item) => ( 
        <TodoItem
          ......
          id={item.id}
          onToggle={onToggleTodo}
          onRemove={onRemoveTodo}
        />
        ))
......
const mapDispatchToProps = (dispatch) => {
  return {
    onToggleTodo: (id) => {
      dispatch(toggleTodo(id));
    },
    onRemoveTodo: (id) => {
      dispatch(removeTodo(id));
    }
  };
};

TodoItem

<input ... onClick={() => {onToggle(id)}} />
 <button ... onClick={()=>{onRemove(id)}}>×</button>

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>
.........
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
   onToggle:()=>{
    ownProps.onToggle(ownProps.id);
  },
   onRemove:()=>{
    ownProps.onRemove(ownProps.id);
  } 
  };
};
这是不可能的

 

TodoItem

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>
......
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
    onToggle: () => {
      dispatch(toggleTodo(ownProps.id));
    },
    onRemove: () => {
      dispatch(removeTodo(ownProps.id));
    }
  };
};



作者:余生筑
链接:https://www.jianshu.com/p/e596191ae7bc
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

标签:参数传递,TodoItem,onRemove,dispatch,React,ownProps,onToggle,id
来源: https://blog.csdn.net/hsany330/article/details/90701192