当用户输入关键字时,我有一个搜索栏,我通过使用 fetch 对我的后端服务进行 api 调用来获得相关结果。我正在将来自后端的响应存储在我的状态中。下面是 SearchBarComponent 的代码:
import React from 'react';
import Searchbar from 'material-ui-search-bar';
import Redirect from "react-router-dom/es/Redirect";
class SearchBarComponent extends React.Component{
constructor() {
super();
this.state = {
results: [],
dataFetched: false,
keyword: 'pre fetch keyword'
};
this.fetchData = this.fetchData.bind(this);
};
render() {
if (this.state.dataFetched) {
return (
<Redirect to = {{
pathname: '/results',
state: {data: this.state.results}
}}/>
)
}
return (
<Searchbar
onChange = {(value) => this.setState({keyword: value})}
onRequestSearch={() => {
this.fetchData(this.state.keyword);
}
}
/>
)
}
fetchData (keyword) {
let url = 'http://localhost:8080/search?name='+encodeURI(keyword);
console.log(url);
fetch(url,{
mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
})
.then(response => {
return response.json()})
.then(data => {
this.setState({results: data, dataFetched: !this.state.dataFetched});
})
}
}
export default SearchBarComponent;
在此之后,我想将我的结果传递给我的 SearchResultsComponet,以便我可以以类似谷歌的方式呈现结果。这就是我将传递的状态收集到我的 SearchResultComponent 中的方式:
import React from 'react';
class SearchResultComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
results: this.props.location.state.data.results
}
}
render() {
return(
<div>
<h4>{this.state.results}</h4>
</div>
)}
}
export default SearchResultComponent
我在这条线上遇到了错误,results: this.props.location.state.data
我无法弄清楚出了什么问题。任何帮助深表感谢。我正在通过我的 index.js 文件处理路由,如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import ResultsPage from './Pages/ResultsPage'
import {Route, BrowserRouter as Router} from 'react-router-dom';
const routing = (
<Router>
<div>
<Route exact path={'/'} component={App}/>
<Route path={'/results'} component={SearchResultComponent}/>
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById('root'));