简体   繁体   English

在React中破坏状态/道具

[英]Destructuring state/props in React

I'm learning React and I have Eslint installed in my project. 我正在学习React,我在项目中安装了Eslint。 It started giving me errors like 它开始给我错误

Use callback in setState when referencing the previous state. (react/no-access-state-in-setstate)
Must use destructuring state assignment (react/destructuring-assignment)

I tried to look this up but couldn't understand properly. 我试着查看一下,但无法正确理解。

Can someone point me in the right direction with this? 有人能指出我正确的方向吗?

Here is my code that throws the errors: 这是我抛出错误的代码:

class LoginForm extends React.Component {
  state = {
    data: {
      email: "",
      password: "",
    },
    loading: false,
    errors: {},
  };

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

  onSubmit = () => {
    const errors = this.validate(this.state.data);
    this.setState({ errors });

    if (Object.keys(errors).length === 0) {
      this.setState({ loading: true });
      this.props
        .submit(this.state.data)
        .catch(err =>
          this.setState({
            errors: err.response.data.errors,
            loading: false,
          }),
        );
    }
  };
}

As I understand I would need to destructure this.state and this.props but how? 据我所知,我需要解构this.statethis.props但如何?

EDIT: After following the suggestions below, I ended up with this. 编辑:按照下面的建议后,我最终得到了这个。 All I need to fix right now is the props. 我现在需要解决的就是道具。 Its asking me to use a destructuring props assignment. 它要求我使用解构道具作业。

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

onSubmit = () => {
    const { data } = this.state;
    const errors = this.validate(data);
    this.setState({ errors });

    if (Object.keys(errors).length === 0) {
        this.setState({ loading: true });
        this.props
            .submit(data)
            .catch(err =>
                this.setState({ errors: err.response.data.errors, loading: false })
            );
    }
};

Thanks in advance and sorry for the newbie question. 提前致谢并抱歉新手问题。

What eslint is telling you with the react/destructuring-assignments error is that assignments like: 什么eslint告诉你的react/destructuring-assignments错误是这样的分配:

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: react/no-access-state-in-setstate的下一个错误告诉您正在编写:

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: 或者,如果您将其与react/destructuring-assignments规则结合使用:

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

You can read more on those two rules here: 您可以在此处详细了解这两条规则:

react/destructuring-assignment 反应/解构赋值

react/no-access-state-in-setstate 反应/无存取状态中,setstate这

Destructuring is basically syntatic sugar Some Eslint configurations prefer it (which I'm guessing is your case). 解构基本上是合成一些Eslint配置更喜欢它(我猜是你的情况)。

It's basically declaring the values and making them equal to the bit of syntax you don't want to repeat, for Ex, given react props: 它基本上是声明值并使它们等于你不想重复的语法,对于Ex,给出了反应道具:

this.props.house, this.props.dog, this.props.car

destructured ---> 结构化--->

 const { house, dog, car } = this.props;

So now you can just use house, or dog or whatever you want. 所以现在你可以使用房子,狗或任何你想要的东西。 It's commonly used with states and props in react , here is more doc about it, hope it helps. 它通常用于状态和道具的反应 ,这里有更多关于它的文档,希望它有所帮助。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

This is problem with your onChange method. 这是你的onChange方法的问题。 Try something like this: 尝试这样的事情:

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

And look at section "State Updates May Be Asynchronous" from https://reactjs.org/docs/state-and-lifecycle.html https://reactjs.org/docs/state-and-lifecycle.html查看“状态更新可能异步”部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM