javascript - 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 时更新,但事实并非如此。
经过一些研究,我能收集到的最好的结果是人们在异步执行操作时遇到了同样的问题,但我还没有找到一个明确的解决方案来解决我的确切问题(我发现的大部分帮助是语法错误,我认为我是自由的。
提前感谢您的帮助 - 我真诚地感谢它!
解决方案
回调仅在componentDidMount
组件安装在 DOM 中时运行,这是您在案例中第一次加载页面。对状态的后续更改不会导致它再次被挂载。由于您要更改的只是quotePos
状态的一部分,quote
并且这些author
部分不会更改,因此使用它们的部分不会在以下渲染中更新。
您可能希望将整个结果集从您所做的获取中保持componentDidMount
在状态,并quotePos
在您的渲染中使用正确的读取。
推荐阅读
- sql-server - 将随机名称作为 SQL 值插入
- django - django模型关系如何将模型A两次链接到模型B
- swift - Swift Dictionary allKeys 顺序
- c# - 如何在 c# 和 COM 对象中管理内存
- bash - 使用正则表达式和“查找”命令查找 *.cpp、*.hpp、*.c 和 *h 文件
- mongodb - 如何在 MongoDB 中插入多个小文件(<16 MB)?
- python - Python:如何编写虚拟环境构建和激活脚本?
- html - 如何根据其他 2 个项目对齐项目?
- angular - 如何在角度的ngIf中使用OR条件?
- flash - 这里的任何人都足以记住 ActionScript 2.0 - 颜色叠加问题