当我在表单输入上按enter键时,有人能告诉我如何在功能组件中使用react router重定向到某个路径吗?我还想把作为道具输入的东西传递给组件
此外,没有提交按钮,只有输入字段
我的代码真的很糟糕,我不知道我在做什么,但它在这里:
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Index from '../containers/Index';
import User from '../containers/User';
const App = () => {
return (
<Router>
<Switch>
<Route path='/' exact component={Index} />
<Route path='/:user' component={User} />
</Switch>
</Router>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
索引.js
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
const index = () => {
const [userState, setUserState] = useState(undefined);
useEffect(() => {
setUserState({ user: user });
console.log(userState);
}, []);
let user;
const handleUser = event => {
event.preventDefault();
user = event.target.value;
};
console.log(user);
return (
<div>
<h1>github stats</h1>
<form
onSubmit={e => {
e.preventDefault();
user = e.target.value;
console.log(user);
}}
>
<input type='text'></input>
</form>
</div>
);
};
export default index;
User.js
import React, { useState, useEffect } from 'react';
const axios = require('axios');
const user = props => {
// console.log(props.username);
const [userState, setUserState] = useState({ user: undefined });
const token = 'personal access token';
const query = `
{
user(login: "${props.username}"){
name
login
avatarUrl
repositories(first: 10 orderBy:{
field: STARGAZERS
direction: DESC
}){
edges{
node{
name
}
}
}
}
}`;
useEffect(() => {
fetchUser();
}, []);
const fetchUser = async () => {
let response = await axios.post(
'https://api.github.com/graphql',
{ query: query },
{ headers: { Authorization: `Bearer ${token}` } }
);
let { data } = response.data;
console.log(data);
};
return <div>hello</div>;
};
export default user;
首先,我认为第二条路由应该如下所示,以便获取user
作为路由参数
<Route path='/user/:user' component={User} />
然后在Index.js表单onSubmit中执行以下操作:
location.replace(`/user/${user}`);
最后在User.jsdo:中
user(login: "${props.match.params.user}") {...