React 零碎笔记

1.对数组的 添加、更新、删除 

 React 对 state里的 array对象 作添加操作时,可以使用 spread 代替 push,并且可以简单调整插入数据的位置,比如数组的开头:

const posts = [...this.state.posts];
posts.push(post);
this.setState({posts});

=>

const posts = [post, ...this.state.posts];
this.setState({posts});

React 更新 state 时,对传递过来的参数在写入时也要 copy

handleUpdate = async post => {
  post.title = 'updated';
  await axios.put(`${apiEndpoint}/${post.id}`, post);
  const posts = [...this.state.posts];
  const index  = posts.indexOf(post);
  posts[index] = {...post}; // write copy it!
  this.setState(posts);
};

  

React 的删除操作时,如果对参数或 state 属性,只是读取而不写入,则无须 copy

handleDelete = async post => {
  await axios.delete(`${apiEndpoint}/${post.id}`);
  const posts = this.state.posts.filter((item) => item.id !== post.id);
  this.setState({posts})
};

  

2.React 中定义事件,先执行{}表达式,获取返回值再绑定到 click 事件

onClick={this.itemClick(88)}

所以,这里应该声明一个函数,会声明一个函数引用,而不是直接执行。

<button onClick={() => this.dltHandler(index)}>Delete</button>

<button onClick={this.dltHandler.bind(this, index)}>Delete</button>

  

233

猜你喜欢

转载自www.cnblogs.com/lemos/p/10921241.html