React 零碎笔记

博客主要介绍了React相关知识,包括对数组的添加、更新、删除操作;为提升性能,多个setState会合并成一次,其具有异步性,使用时需注意值的引用问题;还阐述了定义事件与传参的方法,如声明式定义、绑定this及传参方式等。

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

转载于:https://www.cnblogs.com/lemos/p/10921241.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值