我们正在使用react-router-dom配置项目。我创建了一个代码,使图标根据呈现的页面而有所不同,但是在setState部分中发生无限循环。救救我。
class Bottom extends React.Component {
state = {
iconName : 'initialIconName'
}
setIconName = (name) => {
this.setState(() =>({
iconName: name
}))
}
render() {
const oddEvent = (match, location) => {
if (!match) return false
console.log(location.pathname.substr(1).split('/')[0])
this.setState(() => ({
iconName: location.pathname.substr(1).split('/')[0]
}))
}
return (
<fragment>
<div className="bottom noright">
<div className="bottomcontents">
<div className="bottomicon">
<NavLink className="bottomiconinside bottomiconinsideside" src={home} exact to="/" isActive={oddEvent}>
<img className="iconcenter" src={require(`./home${this.state.iconName == 'home' ? 'sel' : ''}.svg`)}/>
</NavLink>
<NavLink className="bottomiconinside bottomiconinsideside" exact to="/search" isActive={oddEvent}>
<img className="iconcenter" src={require(`./search${this.state.iconName == 'search' ? 'sel' : ''}.svg`)}/>
</NavLink>
<NavLink className="bottomiconinside bottomiconinsideside" to="/add" isActive={oddEvent} >
<img className="iconcenter" src={require(`./add${this.state.iconName == 'add' ? 'sel' : ''}.svg`)}/>
</NavLink>
<NavLink className="bottomiconinside bottomiconinsideside" to="/account" isActive={oddEvent}>
<img className="iconcenter" src={require(`./account${this.state.iconName == 'account' ? 'sel' : ''}.svg`)}/>
</NavLink>
<NavLink className="bottomiconinside bottomiconinsideside" exact to="/setting" isActive={oddEvent}>
<img className="iconcenter" src={require(`./setting${this.state.iconName == 'setting' ? 'sel' : ''}.svg`)}/>
</NavLink>
</div>
{/* <div className="search"></div>
<div className="plus"></div>
<div className="mypage"></div>
<div className="setting"></div> */}
</div>
</div>
</fragment>
);
}
}
export default Bottom;
答案 0 :(得分:0)
React的组件中有所谓的lifecycles
。设置状态后,组件将重新渲染。因此,您不能在setState()
,render()
等内部使用componentDidUpdate()
方法。否则,组件将设置一个新状态,再次渲染,设置一个新状态,再次渲染...
答案 1 :(得分:0)
使用reactJS时要记住一个非常重要的事情。除非shouldComponentUpdate()返回false,否则setState()将始终导致重新渲染。请勿使用setState IN,
在前三个组件中调用setState将导致您进入无限循环,而第4个组件甚至不会留下要渲染的组件