表单提交后反应路由器重定向

React router redirect after form submit

当我在表单输入上按回车键时,谁能告诉我如何使用功能组件中的 React 路由器重定向到特定路径,我还想将输入的任何内容作为道具传递给组件

此外,只有输入字段没有提交按钮

我的代码真的很糟糕,我不认为我知道我在做什么,但它是:

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'));

Index.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.js 中执行:

user(login: "${props.match.params.user}") {...