【发布时间】:2019-10-23 01:07:10
【问题描述】:
当用户输入关键字时,我有一个搜索栏,我通过使用 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,以便我可以以类似 google 的方式呈现结果。这就是我将传递的状态收集到我的 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'));
【问题讨论】:
-
我已经编辑了代码,但仍然收到相同的错误 =>“无法读取未定义的属性‘状态’”。实际上,问题在于我将结果组件的状态与搜索组件的传递状态分配在一起
-
尝试在 SearchResultComponent 的构造函数中添加一个 console.log。然后可以看到this.props.location.state.data.results的哪一部分是未定义的,所以启动this.props.location,然后尝试this.props.location.state,然后this.props.location.state.data,到进一步排除组件树或反应路由器中的错误。并检查来自 fetchData api 调用的数据的形状,它可能与预期不同??
标签: reactjs react-router react-component react-state