gpt4 book ai didi

javascript - 如何通过history.push将对象发送到我重定向到的页面| react

转载 作者:行者123 更新时间:2023-12-01 01:47:59 25 4
gpt4 key购买 nike

我有一个来自搜索栏的对象(结果),我正在尝试通过history.push发送到搜索结果页面,但我无法通过我所在页面上的 Prop 访问该对象重定向到。对我来说,重定向到下一页并能够访问我尝试发送到那里的结果的最简单方法是什么。

import React, {Component} from 'react';
import {Search, List, Form} from 'semantic-ui-react';
import {browserHistory,withRouter} from "react-router-dom"
import axios from 'axios';

class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {query: '', results: [], isLoading: false}
}

componentWillMount() {
this.resetComponent()
}

resetComponent = () => this.setState({ isLoading: false, results: [], query: '' })

search(query) {
this.setState({ query });
axios
.get(`/api/search?query=${query}`)
.then(response => {
this.setState({ results: response.data});
})
.catch(error => console.log(error));
}

handleFormSubmit = () => {
console.log('search:', this.state.query);
this.props.action
this.props.history.push({pathname: `/search/${this.state.query}`, results: `${this.state.results}`})
this.resetComponent()



}


handleInputChange = (query) => {
this.search(query);
this.setState({ isLoading: true, query })

setTimeout(() =>
this.setState({
isLoading: false,
}) , 300)

}

handleResultSelect = (e, { result }) => this.setState({ query: result.title} )

render () {

const resultRenderer = ({ title }) => <List content = {title}/>
return (

<Form onSubmit={this.handleFormSubmit}>
<Search
loading={this.state.isLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={(event) => {this.handleInputChange(event.target.value)}}
showNoResults={false}
value={this.state.query}
resultRenderer={resultRenderer}
results ={this.state.results}
type={"submit"}
{ ...this.props} />
</Form>

);
}

}


export default withRouter (SearchBar)

最佳答案

您可以通过两种方式使用 history.push:使用 2 个参数、一个路径和一个可选状态 history.push(path, [state])location 对象,包含一个或多个属性 {pathname, search, hash, state}。无论采用哪种方式,将自定义数据发送到下一个位置的方式都是通过位置对象的状态。您已经很接近了,只需更改此行:

this.props.history.push({pathname: `/search/${this.state.query}`, results: `${this.state.results}`})

至此

this.props.history.push({pathname: `/search/${this.state.query}`, state: {results: `${this.state.results}`}})

然后您可以通过 props.location.state 访问下一个组件中的数据

关于javascript - 如何通过history.push将对象发送到我重定向到的页面| react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51813305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com