Destructuring state/props in React

前端 未结 3 1093
既然无缘
既然无缘 2021-02-06 11:54

I\'m learning React and I have Eslint installed in my project. It started giving me errors like

Use callback in setState when referencing the previous state. (r         


        
3条回答
  •  误落风尘
    2021-02-06 12:34

    What eslint is telling you with the react/destructuring-assignments error is that assignments like:

    const data = this.state.data;
    

    can be rewritten into:

    const { data } = this.state;
    

    This also works for function arguments, so:

    onChange = e => { ... }
    

    can be written as

    onChange = ({target: {value, name}}) => { ... }
    

    The next error for react/no-access-state-in-setstate tells you that you are writing:

    this.setState({
        data: { ...this.state.data, [e.target.name]: e.target.value }
    });
    

    when you should be writing:

    this.setState(prevState => ({
        data: { ...prevState.data, [e.target.name]: e.target.value }
    }));
    

    or, if you combine it with the react/destructuring-assignments rule:

    onChange = ({target: {name, value}}) =>
        this.setState(prevState => ({
            data: { ...prevState.data, [name]: value }
        }));
    

    You can read more about those two rules here:

    react/destructuring-assignment

    react/no-access-state-in-setstate

提交回复
热议问题