state 。 State包含应用程序需要了解的任何数据,这些数据可能会随时间而变化。您希望应用程序响应状态更改并在必要时显示更新的UI。 React为现代Web应用程序的状态管理提供了一个很好的解决方案。您可以通过在constructor声明组件类的state属性来在React组件中创建状态。这与初始化该组件state被创建时。 state属性必须设置为JavaScript object 。声明它看起来像这样: this.state = {
//在这里描述你的州
您可以在组件的整个生命周期内访问state对象。您可以更新它,在UI中呈现它,并将其作为道具传递给子组件。state对象可以像您需要的那样复杂或简单。请注意,您必须通过扩展React.Component来创建类组件,以便创建这样的state。
state呈现name属性。但是,没有定义state 。初始化与组件state的constructor ,并指定你的名字的属性name 。 StatefulComponent应该存在并呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find("StatefulComponent").length === 1; })(), "StatefulComponent should exist and render.");'
- text: StatefulComponent应该呈现div和h1元素。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find("div").length === 1 && mockedComponent.find("h1").length === 1; })(), "StatefulComponent should render a div and an h1 element.");'
- text: 应使用设置为字符串的属性name初始化StatefulComponent 。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return ( typeof initialState === "object" && typeof initialState.name === "string"); })(), "The state of StatefulComponent should be initialized with a property name set to a string.");'
- text: StatefulComponent的属性name应在h1元素中呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return mockedComponent.find("h1").text() === initialState.name; })(), "The property name in the state of StatefulComponent should render in the h1 element.");'
```