首页 > 其他 > 详细

React 零碎笔记

时间:2019-05-25 10:25:36      阅读:198      评论:0      收藏:0      [点我收藏+]

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>

  

在高阶组件中不要使用箭头函数,如果该回调函数作为一个父类属性传递到低阶组件中

onDelete={() => handleDelete(counter.id)}

当该高阶组件重新渲染时,都会创建一个不同的回调函数,导致属性值的变化,引起低阶组件额外的重新渲染。因此在高阶组件中通常使用 bind 语法或 React 中特有的 属性初始化器语法,来处理事件函数。

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log(‘this is:‘, this);
  }


  render() {
    return (
      <Button onDelete={this.handleClick}>
        Click me
      </Button>
    );
  }
}

 

  

 

233

React 零碎笔记

原文:https://www.cnblogs.com/lemos/p/10921241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!