render()
方法中的state
数据。您可以使用this.state
访问数据。如果要在render方法的return
中访问状态值,则必须将值括在花括号中。 State
是React中组件最强大的功能之一。它允许您跟踪应用程序中的重要数据并呈现UI以响应此数据中的更改。如果您的数据发生变化,您的UI将会发生变化React使用所谓的虚拟DOM来跟踪幕后的变化。当状态数据更新时,它会触发使用该数据重新呈现组件 - 包括作为道具接收数据的子组件。 React更新实际的DOM,但仅在必要时更新。这意味着您不必担心更改DOM。您只需声明UI应该是什么样子。请注意,如果使组件有状态,则其他组件不会知道其state
。它的state
是完全封装的,或者是该组件的本地状态,除非您将状态数据作为props
传递给子组件。这种封装state
概念非常重要,因为它允许您编写某些逻辑,然后在代码中的某个位置包含和隔离该逻辑。 MyComponent
已经是有状态的。在组件的render方法中定义h1
标记,该方法从组件的状态呈现name
的值。 注意: h1
应该只从state
呈现值而不是其他内容。在JSX中,您使用花括号{ }
编写的任何代码都将被视为JavaScript。因此,要从state
访问值,只需将引用括在花括号中。 MyComponent
应该有一个键name
,其freeCodeCamp
值存储在其状态中。
testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "freeCodeCamp", "MyComponent
should have a key name
with value freeCodeCamp
stored in its state.");'
- text: MyComponent
应该渲染一个包含在单个div
的h1
标头。
testString: 'assert(/MyComponent
should render an h1
header enclosed in a single div
.");'
- 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(firstValue === "h1
header should contain text rendered from the component's state.");};'
```
## Challenge Seed