React ES6 优化笔记

以下内容为最近一段时间使用React的优化笔记

1. 使用解构传递参数

const AddPlayerForm = ({ values, onSubmit, onChange }) => {

    return (…)

}

2. promise函数中不一定要使用_this


          .then(response => {
              if(this.isMountedDone) {
                  this.setState({
                      options: response.data
                  });
              }

3.     Stop Memory Leaks with componentWillUnmount Lifecycle Method in React

    componentDidMount() {
        this.isMountedDone = true;
        if(this.props.loadByDb===”true”){
            this.loadData();
        }

    };
    
    componentWillUnmount(){
        this.isMountedDone = false;
    }

loadData(){
        let url = Global.serverpath+’/api/v1/postlogin/sysparameters’;
         axios.get(url, {
            params: {
              module_key:this.props.module_key,
              value_key:this.props.value_key
            },
            headers: {
              “lira_token”: Global.getCookie(‘lira_token’)
            }
          })
          .then(response => {
              if(this.isMountedDone) {
                  this.setState({
                      options: response.data
                  });
              }
          }).catch(function (error) {
            alert(“load error”+JSON.stringify(error));
          });
    }

4. JSX 中使用if else

{errors.name && <AlertBox>{errors.name}</AlertBox>}

上面语句的语义在于, 先执行errors.name 如果返回为true, 则继续执行<AlertBox>, 而AlertBox实际是一个调用

反之, 使用 || 

{errors.name || <AlertBox>{errors.name}</AlertBox>}

如果errors.name已经返回了true, 则 or 后面的内容会被忽略

5. Component引用与调用

下面的例子是一个对于PlayerForm的引用

<Formik>

{PlayerForm}

</Formik>

下面是调用

<Formik>

    <div>{PlayerForm}</div>

</Formik>

区别在于一个传递的是引用,类似<Test callback={myfunction} />

另一个传递的是调用后的返回值(当然如果是一个方法也没有问题)<Test callback={myfunction()} />

6. 拼接字符串

this.setState({ players: […this.state.players, player] });