React(dispatch and parameter passing)

  • Only two forms are allowed
onClick={fn};

or

onClick={()=>{fn()}};
//onClick={()=>{fn(id)}};
  • You can't write that
onClick={fn(id)};
  • in addition
onClick={()=>{fn()}};

Equivalent to

onClick={fn};
  • The first writing method (dispatch by parent component, parameter does not flow into TodoItem)

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>
//It's stupid to write that

or

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

or

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>
......
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
   onToggle:()=>{
    ownProps.onToggle();
  },
   onRemove:()=>{
    ownProps.onRemove();
  } 
  };
};
  • The second writing method (from the parent component dispatch, the parameter flows into TodoItem)
    TodoList
 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>

or

<input ... onClick={onToggle} />
 <button ... onClick={onRemove}>×</button>
.........
const mapDispatchToProps = (dispatch,ownProps) => {
  return {
   onToggle:()=>{
    ownProps.onToggle(ownProps.id);
  },
   onRemove:()=>{
    ownProps.onRemove(ownProps.id);
  } 
  };
};
  • The third writing method (from the sub component dispatch, parameters do not flow into TodoItem)
It's impossible
  • The fourth writing method (from the sub component dispatch, the parameter flows into TodoItem)
    TodoList

 

TodoItem

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



Author: Zhushi for the rest of his life
Link: https://www.jianshu.com/p/e596191ae7bc
Source: Jianshu
The copyright of the brief book belongs to the author. For any reprint, please contact the author for authorization and indicate the source.

Keywords: REST

Added by nads1982 on Sun, 03 Nov 2019 05:11:11 +0200