首页 > 解决方案 > 使用句柄提交和传递消息反应重定向到页面

问题描述

我正在尝试构建一个简单的网站,它接收一条消息,并在提交后将 url 中的消息传递到下一页。

以下是我到目前为止所拥有的,它不会将我的信息传递到我的welcomePage


class HomePage extends React.Component{
  constructor(props) {
    super(props);
    this.state = {message: ''};
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateInput = this.updateInput.bind(this);
  }
  updateInput(event){
    this.setState({message : event.target.value})
    }
  handleSubmit = e =>  {
    e.preventDefault();
    let msg = this.state.message;
    let path = `/welcome/?message=${msg}/`;
    console.log(path)
    this.props.history.push(path) //trying to redirect to this path with the message
  } 
  render(){
    return (
      <div className='HomePage'>
        <header>Home</header>
        <p>
          Hello, please enter a welcome message: 
          <br/>
          <input type="text"
            className="form-control" 
            name="message"
            onChange={this.updateInput}/>
            <button className="submit" 
              type="submit" 
              onClick={this.handleSubmit}>
                Submit
            </button>
        </p>
      </div>
      );
  }
}

下面是欢迎页面,它应该从主页获取消息并显示,但现在它说欢迎,未定义而不是欢迎,当它为空时,它永远不会收到消息,因为我收到错误。

我还想如果我执行 /welcome/?message=hello%20how%20are%20you 之类的操作,欢迎页面将直接显示该消息,无论我是否进入主页进行输入。

class WelcomePage extends React.Component {
  render(){
  return <p>{`Welcome! ${this.input}`}</p>} //trying to get the message from the url here, so it displays
}

标签: javascriptreactjsredirect

解决方案


从哪里来this.input?它无处不在,所以它的价值当然是不确定的。

你应该通过解析 url 来获取消息值,你可以试试这个:

class WelcomePage extends React.Component {
  render() {
    const msg = new URLSearchParams(window.location.search).get('message')
    return <p>{`Welcome! ${msg}`}</p>
  }
}

在https://codesandbox.io/s/goofy-villani-2rnc8?file=/src/App.js中使用 react-router(v5.2.0) 的完整示例代码:

import React from "react";
import { Router, Route, Switch, withRouter } from "react-router";
import "./styles.css";

import { createBrowserHistory } from "history";

const customHistory = createBrowserHistory();

export default function App() {
  return (
    <Router history={customHistory}>
      <Switch>
        <Route exact path="/">
          <HomePage />
        </Route>
        <Route path="/welcome">
          <WelcomePage />
        </Route>
      </Switch>
    </Router>
  );
}

class _HomePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: "" };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateInput = this.updateInput.bind(this);
  }
  updateInput(event) {
    this.setState({ message: event.target.value });
  }
  handleSubmit = e => {
    e.preventDefault();
    let msg = this.state.message;
    let path = `/welcome?message=${msg}`;
    console.log(path);
    this.props.history.push(path); //trying to redirect to this path with the message
  };
  render() {
    return (
      <div className="HomePage">
        <header>Home</header>
        <p>
          Hello, please enter a welcome message:
          <br />
          <input
            type="text"
            className="form-control"
            name="message"
            onChange={this.updateInput}
          />
          <button className="submit" type="submit" onClick={this.handleSubmit}>
            Submit
          </button>
        </p>
      </div>
    );
  }
}

const HomePage = withRouter(_HomePage);

class _WelcomePage extends React.Component {
  render() {
    const msg = new URLSearchParams(this.props.location.search).get("message");
    console.log(msg);
    return <p>{`Welcome! ${msg}`}</p>;
  }
}

const WelcomePage = withRouter(_WelcomePage);

推荐阅读