【问题标题】:How to Set State with arguments passed to a function in React如何使用传递给 React 中的函数的参数设置状态
【发布时间】:2018-07-22 21:20:52
【问题描述】:

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

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

孩子:

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

家长:

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>
    )
  }
}

我敢肯定这是小事,但任何帮助将不胜感激!

【问题讨论】:

  • 如果您将回调函数作为道具传递,有一种方法可以做到这一点,但首先,为什么一个出版物将标题作为参数,而其余的则没有?

标签: javascript reactjs components state react-props


【解决方案1】:

问题可能是您期望this.setState 是同步的。请参阅documentation here

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

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

【讨论】:

  • 谢谢!这行得通!我在 this.setState 的末尾添加了一个回调函数,显示我的状态实际上正在正确更新
猜你喜欢
  • 2021-01-06
  • 2020-04-26
  • 1970-01-01
  • 2015-08-16
  • 2020-04-05
  • 1970-01-01
  • 2019-12-16
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多