javascript - 当内容嵌套在数组中时,React 看不到“标记更改”
问题描述
我遇到的问题是 React 在以下情况下没有更新。
当组件应该更新时,我添加了一个 forceUpdate() 以确保更加确定。
代码很简单,所以没什么好说的。
就好像 React 没有看到它应该更新或者我在这里做错了什么?
class Greetings extends React.Component{
constructor(props){
super(props)
this.switchLanguage = this.switchLanguage.bind(this)
this.state = {
languageID: 0,
}
this.arrayContainingRenderValues = [
<span>{this.props.greetingArray[this.state.languageID]}!</span>,
<span>No greetings for you!!</span>
]
}
switchLanguage(){
this.setState((previousState) => ({languageID: (previousState.languageID + 1) % this.props.greetingArray.length}))
this.forceUpdate()
}
componentDidMount(){
this.timerID = setInterval(this.switchLanguage, 500)
}
componentWillDismount(){
clearInterval(this.timerID)
}
render(){
return this.arrayContainingRenderValues[0]
//The return below works without problem
return <span>{this.props.greetingArray[this.state.languageID]}!</span>
}
}
let content = <Greetings greetingArray={["Good morning","Bonjour","Buenos días","Guten tag","Bom dia","Buongiorno"]}/>
ReactDOM.render(content, document.getElementById('root'))
啊,这段代码是一个例子,我真的不需要它来工作,但如果它需要它会很好。谢谢。
解决方案
问题
当您this.arrayContainingRenderValues
在构造函数中定义时,您包含了当前/初始this.state.languageID
值,因此this.state.languageID
以后的任何更新都不会更新这个陈旧的外壳。this.arrayContainingRenderValues
每次状态更新时,您都希望重新计算值。当您移动数组进行渲染时,您每次都在重新计算。
解决方案
this.props.greetingArray
如果为空(或未通过),您似乎正在尝试应用一些条件渲染。
class Greetings extends React.Component {
constructor(props) {
super(props);
this.switchLanguage = this.switchLanguage.bind(this);
this.state = {
languageID: 0
};
}
switchLanguage() {
this.setState((previousState) => ({
languageID:
(previousState.languageID + 1) % this.props.greetingArray.length
}));
}
componentDidMount() {
this.timerID = setInterval(this.switchLanguage, 500);
}
componentWillDismount() {
clearInterval(this.timerID);
}
render() {
return this.props.greetingArray.length ? (
<span>{this.props.greetingArray[this.state.languageID]}!</span>
) : (
<span>No greetings for you!!</span>
);
}
}
演示
推荐阅读
- python - 将 Python gui 窗口放在前面?
- vb.net - 如何在 VB.net 中显示 .txt 文件的内容并进行比较
- php - 尝试呈现内容时出现白页
- haskell - 使用 postgresql-simple 查询字符串的类型错误
- asp.net-mvc - Azure Active Directory 身份验证问题
- angular - 位置 437 的 JSON 中的意外标记 }
- python - 比较列表python列表的元素
- sql - 查找重叠的日期范围并从事实表中删除重复项
- ballerina - 如何在 Ballerina 中丰富 JSON 数组
- javascript - Angular - 无法解析服务的所有参数(?)