首页 > 解决方案 > React 组件未通过状态更新重新渲染

问题描述

我在 React 组件未更新时遇到了一些问题,即使我可以确认状态正在更新。

Codepen 的链接在这里:https ://codepen.io/paalpwmd/full/WNveejG

  constructor(props){
    super(props)
    this.state = {
    }   
  }


  render(){
      return(
        <div>
          <a href="https://twitter.com/intent/tweet" id="tweet-quote">Tweet me</a>
        </div>
      )
    }
}

class QuoteBody extends React.Component{
  constructor(props){
    super(props)
    this.refreshQuote = this.refreshQuote.bind(this);
    this.state = { quote: "", author: "", quotePos: 0 };
  } 


refreshQuote() {
    let n = Math.floor(Math.random() * (120 - 0 + 1) + 0);
    this.setState({
    quotePos: n
    });
  console.log(this.state.quotePos)
  }

  render(){
    return(
      <div>
      <button id="new-quote" onClick={this.refreshQuote}>New Quote!</button>
      <div id="text"> 
      <p>{this.state.quote}</p>
        </div>
            <div id="author">
        <p>{"- " + this.state.author}</p>
        </div>
        <TwitterButton />
        </div>
    )
  }
componentDidMount() {
    fetch("https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json")
      .then(res => res.json())
      .then(
        (result) => {
          let i = this.state.quotePos;
          this.setState({
            quote: result.quotes[i].quote,
            author: result.quotes[i].author
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
}

const QuoteBox = document.getElementById("quote-box")
ReactDOM.render(<QuoteBody />, QuoteBox);

我对 React 很陌生,所以我不完全确定我做错了什么,所以我分享了整个项目。

我希望 QuoteBody 组件在运行 refreshQuote 时更新,但事实并非如此。

经过一些研究,我能收集到的最好的结果是人们在异步执行操作时遇到了同样的问题,但我还没有找到一个明确的解决方案来解决我的确切问题(我发现的大部分帮助是语法错误,我认为我是自由的。

提前感谢您的帮助 - 我真诚地感谢它!

标签: javascriptreactjs

解决方案


回调仅在componentDidMount组件安装在 DOM 中时运行,这是您在案例中第一次加载页面。对状态的后续更改不会导致它再次被挂载。由于您要更改的只是quotePos状态的一部分,quote并且这些author部分不会更改,因此使用它们的部分不会在以下渲染中更新。

您可能希望将整个结果集从您所做的获取中保持componentDidMount在状态,并quotePos在您的渲染中使用正确的读取。


推荐阅读