我正在做Nav反应组件里面的Filter组件。组件已挂载时,我开始查看当前的URL,然后,如果它不是/ home,我隐藏了Filter组件。代码工作得非常好,导航组件在需要时会更改状态。代码如下所示:
class Nav extends Component {
constructor (props) {
super(props)
this.state = {
isHome: true
}
}
componentDidMount() {
this.timerID = setInterval(this.checkUrl, 10)
}
componentWillUnmount() {
clearInterval(this.timerID)
}
checkUrl = () => {
if(!this.state.isHome && this.location === '/home') {
this.setState({isHome: true})
}
if(this.state.isHome && this.location !== '/home') {
this.setState({isHome: false})
}
}
render () {
return (
...Some other JSX code goes here...
{this.state.isHome ? <Filter /> : null}
...Some other JSX code goes here...
)
}
}
问题是:我每10毫秒调用一次checkURL函数,但这个函数是简单的url检查。这如何影响我的应用程序的生产力?谢谢。
答案 0 :(得分:0)
Actually, I will move all these logic into render function and let React decide when to re-render Filter component.
I notice that you detemind if the Filter component is showed by this.location. It supposed that "this" here refers to window object, so the location here is the url itself.
Two possibilities here:
First, if you use client-side-router (e.g. react-router, universal-router) to take care of your url. You should use API like history push or some html5 history wrapper to sync your state and url.
Second if you do not use client-side-router. Everytime page reload your whole component will re-render.
Eeither way you do not use this.location to determine the Filter component show or not with a checkUrl-like function.