美文网首页
(三)React 代码优化

(三)React 代码优化

作者: 云凡的云凡 | 来源:发表于2020-10-18 12:28 被阅读0次

TodoItem.jsx 的优化

1、content 等价于 this.props

  render () {
    return <div>{this.props.content}</div>;
  }

改成

  render () {
    const {content} = this.props;
    return (
      <div onClick={this.handleClick}>
        {content}
      </div>
    );
  }

  handleClick () {
    console.log (this.props.index);
    this.props.deleteItem (this.props.index);
  }

改成

 handleClick () {
    const {deleteItem, index} = this.props;
    deleteItem (index);
  }

TodoList.jsx 的优化

1.把bind.(this)写到constructor

组件初始化的时候把this指向改好

 constructor (props) {
    super (props);
    this.state = {
      inputValue: '',
      list: [],
    };
    this.handleInputChange = this.handleInputChange.bind (this);
    this.handleBtnClick = this.handleBtnClick.bind (this);
    this.handleItemDelete = this.handleItemDelete.bind (this);
  }

这样用

 <input
            id="insertArea"
            className="input"
            type="text"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />

2.map 优化(代码拆分)

<ul>
            {this.state.list.map ((item, index) => {
              return (
                <TodoItem
                  content={item}
                  index={index}
                  key={index}
                  deleteItem={this.handleItemDelete}
                />
              );
            })}
 </ul>

改成

  <ul>
            {this.getTodoItem ()}
 </ul>
 // 让jsx体积不会过于强大,维护起来更方便
getTodoItem () {
    return this.state.list.map ((item, index) => {
      return (
        <TodoItem
          content={item}
          index={index}
          key={index}
          deleteItem={this.handleItemDelete}
        />
      );
    });
  }

3.新版 setState 可以接收一个函数,而不是一个对象,这个函数需要有一个返回值,返回这个对象。


image.png

 this.setState ({
      inputValue: e.target.value,
    });

改成

 // 因为setState是异步的,所以把value存在外部
 const {value} = e.target;
  this.setState (() => {
      return {
        inputValue: value,
      };
    });

//ES6的写法
 // 因为setState是异步的,所以把value存在外部
    const {value} = e.target;
    this.setState (() => ({
      inputValue: value,
    }));
  1. setState 可以接收 参数,prevState表示修改数据之前的那一次数据的样子
 this.setState ({
      list: [...this.state.list, this.state.inputValue],
      inputValue: '',
    });

改成
更靠谱

this.setState((prevState)=>({
      list: [...prevState.list, prevState.inputValue],
      inputValue: '',
    }))

相关文章

网友评论

      本文标题:(三)React 代码优化

      本文链接:https://www.haomeiwen.com/subject/kkhfmktx.html