react - setState 简写
react - setState in short form
你会写吗
let firstNameValid = this.state.firstNameValid;
firstNameValid = value.length >= 1;
this.setState({ firstNameValid, firstNameValid,})
作为短格式语法
this.setState({ firstNameValid})
上面的代码我试过了,好像没问题。
不知道会不会有副作用?
如果你的意思是你正在写作
this.setState({foo: foo})
现在您正在使用 this.setState({ foo })
没有区别。
但是 setState
很可能会产生副作用,首先是因为它是异步的,其次是因为您正在更改整个组件状态并导致渲染。
顺便说一下,这种分配对象的简短方式是 JS 的一个特性,与 React 无关。
react 使用 ES2015(带有 webpack 和 babel)。
setState 采用对象参数。
在 ES2015 中,{ a : a }
与 { a }
(对象 shorthand 表示法)相同。
所以 x = { a : a, b : b ...}
与 x = { a, b ..}
相同
所以你的代码是完全有效的,不会有任何副作用。
this.setState({ firstNameValid })
只是 this.setState({ firstNameValid: firstNameValid })
的糖。无副作用。
这些称为 shorthand property names
,您可以阅读有关它们的更多信息 here。
你会写吗
let firstNameValid = this.state.firstNameValid;
firstNameValid = value.length >= 1;
this.setState({ firstNameValid, firstNameValid,})
作为短格式语法
this.setState({ firstNameValid})
上面的代码我试过了,好像没问题。 不知道会不会有副作用?
如果你的意思是你正在写作
this.setState({foo: foo})
现在您正在使用 this.setState({ foo })
没有区别。
但是 setState
很可能会产生副作用,首先是因为它是异步的,其次是因为您正在更改整个组件状态并导致渲染。
顺便说一下,这种分配对象的简短方式是 JS 的一个特性,与 React 无关。
react 使用 ES2015(带有 webpack 和 babel)。
setState 采用对象参数。
在 ES2015 中,{ a : a }
与 { a }
(对象 shorthand 表示法)相同。
所以 x = { a : a, b : b ...}
与 x = { a, b ..}
相同
所以你的代码是完全有效的,不会有任何副作用。
this.setState({ firstNameValid })
只是 this.setState({ firstNameValid: firstNameValid })
的糖。无副作用。
这些称为 shorthand property names
,您可以阅读有关它们的更多信息 here。