React 零碎笔记

1.对数组的操作(添加、更新、删除)

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

=>

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

  

2.多个 setState 会合并成一次

为了提升性能,react 会合并多个 setState 方法。造成两个结果:setState 是异步的(不会马上执行),无法在 setState 立即能使用该值(可使用 setState callback);

无法确保 setState 传入的值是当前引用的值(传入的 state 引用可能会变在合并时改变),可使用 值拷贝。

示例:

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})
};

  

3. 定义事件与传参

① 使用声明式方式定义事件:声明一个函数或函数引用。

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

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

  

② 绑定 this

1)属性初始化器

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>
    );
  }
}

2)箭头函数

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

3)bind 函数(绑定上下文与传参)

class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }
    
    preventPop(name, e){    //事件对象e要放在最后
        e.preventDefault();
        alert(name);
    }
    
    render(){
        return (
            <div>
                <p>hello</p>
                {/* Pass params via bind() method. */}
                <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
            </div>
        );
    }
}

  

③ 传参

bind 函数;箭头表达式。

233