如何使用传递给 React 函数的参数来设置状态

How to Set State with arguments passed to a function in React

我正在尝试将数组(标题)从 child 组件传递到 parent,然后使用该数组设置 parent 的状态。但是,在处理 increaseReads() 方法中的更改时,我无法更改 articlesRead 状态

您将看到两个 console.log() 语句;第一个成功记录了标题,但第二个记录了一个空数组——前一个状态

Child:

export class Publication extends React.Component {
  constructor() {
    super();
    this.state = {
      items: []
    };
  }

  componentDidMount() {
    fetch(this.props.url)
    .then(response => {
      return response.json();
    }).then(({ items })=> {
      this.setState({ items });
    });
  }

  handleClick () => {
    this.props.openArticle();
  }


  render() {
    return (
      <div className='publication'>
        <h4>{this.props.name}</h4>
        <ul>
          {this.state.items.map(item => (
           <li><a href={item.link} target='_blank' onClick={this.handleClick}>{item.title}</a></li>
          ))}
        </ul>
      </div>
    );
  }
}

Parent:

export class Latest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      totalReads: 0,
      articlesRead: []
    };
  }

  handleChange = () => {
    this.props.increaseTotal();
  }

  increaseReads(titles) {
    this.setState({
      totalReads: this.state.totalReads + 1,
      articlesRead: titles
    })

    // Won't log correctly
    console.log(this.state.articlesRead);

    this.handleChange();
  }

  render() {
    return (
      <div className='container'>
        <Publication total={(titles) => {this.increaseReads(titles)}} name='Free Code Camp' api={'https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fmedium.freecodecamp.org%2Ffeed%2F'}/>
        <Publication total={() => {this.increaseReads()}} name='Code Burst' api={'https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fcodeburst.io%2Ffeed%2F'}/>
        <Publication total={() => {this.increaseReads()}} name='JavaScript Scene' api={'https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fmedium.com%2Ffeed%2Fjavascript-scene%2F'}/>
        <Publication total={() => {this.increaseReads()}} name='Hacker Noon' api={'https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fhackernoon.com%2Ffeed'}/>
      </div>
    )
  }
}

我确定它很小,但我们将不胜感激!

问题可能是您希望 this.setState 是同步的。见 documentation here.

看看这个CodeSandbox demothis.setState 接受回调作为第二个参数。此回调在 this.setState 完成后调用。

注意如何在 console.log 输出中,我们可以看到 oldnew 状态值。