我是一个新的反应和建立一个小型搜索引擎。从我的主页,我收集用户输入的关键字,然后从后端获取数据,我想在我的结果页面上显示这些数据。但它不会重定向到'/results'页面。这是我的Homepage.js
import React from "react";
import SearchBar from "material-ui-search-bar";
import logo from "../searchpagelogo.png"
import AutoComplete from 'material-ui/AutoComplete';
import Redirect from "react-router-dom/es/Redirect";
class Homepage extends React.Component{
constructor() {
super();
this.state = {
results: [],
dataFetched: false,
keyword: ''
};
this.fetchData = this.fetchData.bind(this);
this.redirect = this.redirect.bind(this);
}
render() {
const searchStyle = {
textAlign: 'center',
width: 800,
margin: '0 auto',
display: 'block'
};
return (
<div style={searchStyle}>
<img src={logo} alt={'homepage application logo'}/>
<br/>
<br/>
<SearchBar
onChange={(value) => this.setState({keyword: value})}
onRequestSearch={() => this.fetchData(this.state.keyword)}
/>
</div>
)
}
fetchData(keyword) {
let url = 'http://localhost:8080/results?q=' + encodeURI(keyword);
fetch(url)
.then(response => response.json())
.then(data => {
this.setState({results: data, dataFetched: !this.state.dataFetched});
console.log(this.state.results)
console.log(this.state.dataFetched)})
.then(() => {
if (this.state.dataFetched) {
console.log("Redirecting to redirect function")
this.redirect()
}
})
}
redirect() {
console.log("Inside Redirect function")
return (
<Redirect to = {{
pathname: '/results',
state: {results: this.state.results}
}}/>
)
}
}
export default Homepage;
我还在index.js文件中添加了react路由器部分。这是,index.js,,我到底做错了什么。任何帮助/建议都是非常感谢的。
请在评论中了解更多信息。
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import SearchResultsPage from './components/SearchResultsPage'
import {Route, Link, BrowserRouter as Router} from 'react-router-dom';
const routing = (
<Router>
<div>
<Route exact path={'/'} component={App}/>
<Route path={'/results'} component={SearchResultsPage}/>
</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
发布于 2019-01-07 03:13:15
重定向在渲染函数中起作用。你可以写
render() {
if(this.state.dataFetched) return (
<Redirect to = {{
pathname: '/results',
state: {results: this.state.results}
}}/>
)
const searchStyle = {
textAlign: 'center',
width: 800,
margin: '0 auto',
display: 'block'
};
return (
<div style={searchStyle}>
<img src={logo} alt={'homepage application logo'}/>
<br/>
<br/>
<SearchBar
onChange={(value) => this.setState({keyword: value})}
onRequestSearch={() => this.fetchData(this.state.keyword)}
/>
</div>
)
}
https://stackoverflow.com/questions/54064909
复制相似问题