state
以及如何在constructor
初始化状态。还有一种方法可以改变组件的state
。 React提供了一种更新名为setState
组件state
的方法。您可以在组件类中调用setState
方法,如下所示: this.setState()
,传入一个具有键值对的对象。键是您的状态属性,值是更新的状态数据。例如,如果我们在状态中存储username
并想要更新它,它将如下所示: this.setState({React希望你永远不要直接修改
用户名:'Lewis'
});
state
,而是在状态发生变化时总是使用this.setState()
。此外,您应该注意React可以批量处理多个状态更新以提高性能。这意味着通过setState
方法的状态更新可以是异步的。 setState
方法有一种替代语法,它提供了解决此问题的方法。这很少需要,但记住它是件好事!有关更多详细信息,请参阅React文档 。 button
元素,它有一个onClick()
处理程序。当button
在浏览器中收到单击事件时,将触发此处理程序,并运行MyComponent
定义的handleClick
方法。在handleClick
方法中,使用this.setState()
更新组件state
。设置name
的属性state
为等于字符串React Rocks!
。单击按钮并观察呈现的状态更新。如果您还不完全了解点击处理程序代码在此时的工作原理,请不要担心。它涵盖了即将到来的挑战。 MyComponent
的状态应使用键值对{ name: Initial State }
。'
testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "Initial State", "The state of MyComponent
should initialize with the key value pair { name: Initial State }
.");'
- text: MyComponent
应该呈现一个h1
标头。
testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).find("h1").length === 1, "MyComponent
should render an h1
header.");'
- text: 渲染的h1
标头应包含从组件状态呈现的文本。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "TestName" }); return waitForIt(() => mockedComponent.html()); }; const firstValue = await first(); assert(/h1
header should contain text rendered from the component's state."); };'
- text: 在MyComponent
上调用handleClick
方法应该将state属性设置为等于React Rocks!
。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "Before" }); return waitForIt(() => mockedComponent.state("name")); }; const second = () => { mockedComponent.instance().handleClick(); return waitForIt(() => mockedComponent.state("name")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === "Before" && secondValue === "React Rocks!", "Calling the handleClick
method on MyComponent
should set the name property in state to equal React Rocks!
."); };'
```