如何根据同级组件设置的URL重新加载React组件?

时间:2018-07-30 09:59:57

标签: javascript reactjs react-router render

我有Main组件,其中包含以下代码,并且工作正常。

<Switch>
<Route path='/compare' component={Compare} />
<Route exact path='/' component={Home} />
<Route path={`/search`} component={Search} />
<Route path={`/:vehicleId`} component={VehicleDetail} />
</Switch>

您在上方看到的Search组件具有一个搜索输入框,使用该输入框将显示搜索结果。我想从“搜索”组件中取出搜索框,然后将其放在我的导航栏中,但是从导航栏中搜索时,在“搜索”组件中显示结果。这就是我的App.js的样子。

<div>
 <Navbar/> <-- search box is here now
 <Main/> <-- I have to show the result in here now, inside Search component
 <Footer/>
</div>

我正在尝试使用以下代码从Navbar组件中设置URL,它可以很好地工作。

this.props.history.push(`/search?q=${query}`)

但是,当我已经在“搜索”页面中时,只会更新URL,但是Search组件不会重新呈现。换句话说,当我从另一个URL搜索时,我可以加载搜索组件,但是一旦我进入domain.com/search?q=mercedes,如果我搜索的是标致更新URL的标致,则搜索结果不会重新呈现。到domain.com/search?q=peugeot,但仍显示最后一次搜索是mercedes的结果。

如何重新呈现Search组件?

其他信息 搜索组件代码如下:

state = {
        query   : (new URL(document.location)).searchParams.get('q'),
        submit  : false,
        result  : []
    }

    componentDidUpdate() {
        if (this.state.submit) {
            let url = `${data.api}api/all/?search=${this.state.query}`
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    this.setState({
                        result : data
                    })
                })
            this.setState({ submit : false })
        }
    }

    componentDidMount() {
        let url = `${data.api}api/all/?search=${this.state.query}`
        fetch(url)
            .then(response => response.json())
            .then(data => {
                this.setState({
                    result : data
                })
            })
    }

这非常好用,因为搜索框位于搜索组件内。但是,当我执行history.push并从同级Navbar组件更新URL时,此代码不起作用。

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为在您的 componentDidUpdate 中,您正在检查this.state.submit是否为假,因此不起作用

从现在开始,在另一个组件中,您需要找到一种方法来将此提交设置为您的状态。

解决方案:

将所有状态和handleClick()处理程序从 Header 移至 MainWrapper组件。 然后将值作为道具传递给需要共享此功能的所有组件。

这样,您可以在MainWrapper组件的状态下设置 submit ,还可以通过prop在子组件中对其进行访问。

相关问题