好的,所以当有人登录时,它应该将他重定向到电话组件。但出于某种原因,它只会将 URL 更改为 /phones 而不会呈现组件。我认为这可能与我使用的 api 有关系 https://app.swaggerhub.com/apis/warp/etn-device-checker-test/1.0#/default/post_login 可能需要令牌但不确定。感谢您的任何建议。
登录.js
import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import { useHistory } from "react-router-dom";
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
let history = useHistory()
const onSubmit = (e) => {
e.preventDefault();
const getIn = {
"login":email,
"password":password,
};
axios
.post('https://js-test-api.etnetera.cz/api/v1/login', getIn,
{
headers: {
'content-type': 'application/json',
}
}).then((res) => {
console.log(res.data);
history.push("/phones");
})
.catch((error) => console.log(error));
};
return (
<div>
<form >
<label>email</label> <input value={email}
onChange={(e) => setEmail(e.target.value)} type="text"/>
<label>password</label> <input type="text" value={password}
onChange={(e) => setPassword(e.target.value)}/>
<button onClick={onSubmit}>login</button>
</form>
</div>
)
}
export default Login
app.js
import './App.css';
import Login from './Login';
import MobileList from './mobileList';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route>
<Login path='/login' exact/>
</Route>
<Route>
<MobileList path='/phones' exact/>
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
mobileList.js
import React from 'react'
import { MobileContext } from './MobileContext';
import { useContext } from 'react';
import Mobile from './Mobile';
function MobileList() {
const { mobiles } = useContext(MobileContext);
return (
<div>
{mobiles.map((item) => (
<Mobile
vendor={item.vendor}
/>
))}
hezasdccccccccccccccc
</div>
)
}
export default MobileList
答案 0 :(得分:1)
您必须在 path
上使用 Route
道具,而不是在其子项上使用:
<Route path='/login' exact>
<Login />
</Route>
<Route path='/phones' exact>
<MobileList />
</Route>