gpt4 book ai didi

javascript - React Redirect 不应在路由器之外使用

转载 作者:行者123 更新时间:2023-12-04 13:21:30 24 4
gpt4 key购买 nike

我对 react 还很陌生,我正在通过创建此示例应用程序来学习自己,在该应用程序中,用户尝试使用凭据登录,成功后,用户应重定向到我可能会显示一些数据的主页。到目前为止,我收到以下错误

Uncaught Error: You should not use <Redirect> outside a <Router>



我的两个组件如下所示

应用程序.js
import React, { Component } from 'react';
import axios from 'axios';
import { Route, Redirect } from 'react-router';
import Home from './Home';
import AuthLogin from './AuthLogin';


class App extends Component {

constructor(){
super();
this.state = {
username: '',
password: '',
userdata: [],
isLogin: false
};

this.handleUserChange = this.handleUserChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event){
event.preventDefault();
axios.post('https://api.github.com/user',{}, {
auth: {
username: this.state.username,
password: this.state.password
}
}).then((response) => {
console.log(response.data);
this.setState({
userdata: response.data,
isLogin:true
});
}).catch(function(error) {
console.log('Error on Authentication' + error);
});
}

handleUserChange(event){
this.setState({
username : event.target.value,
});
}

handlePasswordChange = event => {
this.setState({
password: event.target.value
});
}

render() {
if(this.state.isLogin){
return <Redirect to={{
pathname: 'home',
state: this.state.data
}} />
}
return (
<form onSubmit={this.handleSubmit}>
<label>
username :
<input type="text" value={this.state.username} onChange={this.handleUserChange} required/>
</label>
<label>
password :
<input type="password" value={this.state.password} onChange={this.handlePasswordChange} required/>
</label>
<input type="submit" value="LogIn" />
</form>

);
}
}

export default App;

主页.js
import React, { Component } from 'react';
import axios from 'axios';

class Home extends Component {
state = {
Search:'',
results:[]
}

getInfo = () => {

axios.get('https://api.github.com/search/users',{
params: {
q: this.state.Search,
in:'login',
type:'Users'
}
}).then(({ response }) => {
this.setState({
results: response.data.items.login
})
})
}

handleSearchChange(event){
this.setState({
Search: this.state.Search
}, setInterval(() => {
if (this.state.Search && this.state.Search.length > 1) {
if (this.state.Search.length % 2 === 0) {
this.getInfo();
}
}
},500));

}

render(){
return (
<div>
Home page {this.props.data}

<form>
<label>
Search :
<input type="text" placeholder="Search for..." value={this.state.Search} onChange={this.handleSearchChange} />
</label>
</form>
</div>
);
}
}

export default Home;

我的目标是在成功登录后获得一个页面。

我能得到帮助吗?非常感激。

谢谢

最佳答案

请务必附上您的 <App/><BrowserRouter>在你的 index.js 中。

ReactDom.render(<BrowserRouter><App/></BrowserRouter>,document.getElementById('root'));
(使用: import {BrowserRouter} from 'react-router-dom')

关于javascript - React Redirect 不应在路由器之外使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52159718/

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