首页 > 解决方案 > 在 React 中传递具有 Link 状态的 Props

问题描述

我正在尝试将道具通过Link状态传递给下一个组件,但值为undefined.

class Weather extends Component {
  state = {
    temp1: undefined
  };

  weatherSubmit = async event => {
    event.preventDefault();
    const api_call = await fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=London&apikey=########################"
    );
    const data = await api_call.json();

    this.setState({
      temp1: data.main.temp
    });
    console.log(this.state.temp1);
  };

  render() {
    return (
      <div className="container-weather">
        <form onSubmit={this.weatherSubmit}>
          <label>Input location Name: </label>
          <input type="text" name="weatherInput" />
          <button type="submit">
            <Link
              to={{
                pathname: "/WeatherResult",
                state: { temp1: this.state.temp1 }
              }}
            >
              Submit
            </Link>
          </button>
        </form>
      </div>
    );
  }
}

这里temp1的价值是在undefined哪里给出价值。console.logweatherSubmit

class WeatherResult extends Component {
  state = {};
  render() {
    console.log(this.props.temp1);
    return (
      <div className="container">
        <p>Weather: </p>
        <p>{this.props.temp1}</p>
      </div>
    );
  }
}

标签: reactjsreact-router

解决方案


当您传递数据时Link

<Link
   to={{
       pathname: "/WeatherResult",
       state: { temp1: this.state.temp1 }
   }}
>

您可以将目标组件中的数据检索为,

this.props.location.state.temp1

注意:如果this.state.temp1是一个复杂的对象,那么最好将它字符串化。

<Link
   to={{
       pathname: "/WeatherResult",
       state: { temp1: JSON.stringify(this.state.temp1) }
   }}
>

在目标组件中,您可以像这样检索,

const temp1 = JSON.parse(this.props.location.state.temp1) 

简化演示


更新

如果您在访问对象时仍然遇到错误location,那么您可能正在使用react-router-dom v3. 在这个版本中,您需要使用withRouterHOC 包装您的组件。

import { withRouter } from 'react-router-dom'

class WeatherResult extends Component { ... }

export default withRouter(WeatherResult)

更新 2

你已经包装了你的buttonusing Link,

<button type="submit">
  <Link
    to={{
      pathname: "/WeatherResult",
      state: { temp1: this.state.temp1 }
    }}
  >
    Submit
  </Link>
</button>

使用函数temp1提交表单后,您将在状态变量中获取数据。weatherSubmit

所以只要点击提交按钮,就不会阻塞执行完成weatherSubmit函数的执行,会直接导航到带有 path 的目标组件"/WeatherResult"。因此,在这种情况下,您的weatherSubmit函数没有被执行,并且您在目标组件中获得状态的初始值,即undefined(初始状态)。

解决方案是不要使用包裹按钮Link,保持简单按钮

<button type="submit">
   Submit
</button>

您可以在weatherSubmit函数返回成功并temp1使用 setState 中的回调成功设置状态后导航。

this.setState({
    temp1: data.main.temp
}, () => this.props.history.push({
     pathname: '/WeatherResult',
     state: { temp1: JSON.stringify(this.state.temp1) }
}));

推荐阅读