Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/set-state-with-this.setstate.md
Oliver Eyton-Williams ee1e8abd87 feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

4.4 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a24c314108439a4d4036173 用 this.setState 设置状态 6 301412 set-state-with-this-setstate

--description--

前面的挑战涵盖了组件的state以及如何在constructor中初始化 state。还有一种方法可以更改组件的stateReact 提供了setState方法来更新组件的state。在组件类中调用setState方法如下所示:this.setState(),传入键值对的对象,其中键是 state 属性,值是更新后的 state 数据。例如,如果我们在 state 中存储username,并想要更新它,代码如下所示:

this.setState({
  username: 'Lewis'
});

React 希望你永远不要直接修改state,而是在 state 发生改变时始终使用this.setState()。此外你应该注意React 可以批量处理多个 state 更新以提高性能。这意味着通过setState方法进行的 state 更新可以是异步的。setState方法有一种替代语法可以解决异步问题,虽然这很少用到,但是最好还是记住它!有关详细信息,请参阅React 文档

--instructions--

代码编辑器中有一个button元素,它有一个onClick()处理程序。当button在浏览器中接收到单击事件时触发此处理程序,并运行MyComponent中定义的handleClick方法。在handleClick方法中,使用this.setState()更新组件的state。设置state中的name属性为字符串React Rocks!

单击按钮查看渲染的 state 的更新。如果你不完全理解单击处理程序代码在此时的工作方式,请不要担心。在接下来的挑战中会有讲述。

--hints--

MyComponent的 state 应该使用键值对 { name: Initial State } 来初始化。

assert(
  Enzyme.mount(React.createElement(MyComponent)).state('name') ===
    'Initial State'
);

MyComponent应该渲染一个h1标题。

assert(Enzyme.mount(React.createElement(MyComponent)).find('h1').length === 1);

渲染的h1标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。

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>TestName<\/h1>/.test(firstValue));
};

调用MyComponenthandleClick方法应该将 state 的 name 属性设置为React Rocks!

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!');
};

--seed--

--after-user-code--

ReactDOM.render(<MyComponent />, document.getElementById('root'))

--seed-contents--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    // Change code below this line

    // Change code above this line
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

--solutions--

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
     // Change code below this line
    this.setState({
      name: 'React Rocks!'
    });
    // Change code above this line
  }
  render() {
    return (
      <div>
        <button onClick = {this.handleClick}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};