reactjs - 在 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.log
weatherSubmit
class WeatherResult extends Component {
state = {};
render() {
console.log(this.props.temp1);
return (
<div className="container">
<p>Weather: </p>
<p>{this.props.temp1}</p>
</div>
);
}
}
解决方案
当您传递数据时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
. 在这个版本中,您需要使用withRouter
HOC 包装您的组件。
import { withRouter } from 'react-router-dom'
class WeatherResult extends Component { ... }
export default withRouter(WeatherResult)
更新 2
你已经包装了你的button
using 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) }
}));
推荐阅读
- javascript - JS setTimeout 运行后将图像移回
- node.js - 亚马逊产品广告 API 错误:使用 await 时出现双重回调错误
- c# - 如何在 Unity 2D 中发射子弹?
- javascript - Push 覆盖对象内部数组的内容,但不覆盖外部数据
- c++ - 如何以面向对象的形式(OOP)使用 C++ 递归打印链表
- c++ - 有人可以解释一下 gcc 的 _Bind::call_x() 实现中 cv 限定符的情况吗
- javascript - 如何使用 Stripe Elements 中的 javascript 将元数据传递给 Stripe Webhook
- recursion - 一旦返回所需的值,如何停止序言中的递归?
- ios - 如何使圆形层更大保持中心固定
- haskell - 如何使用与另一个 Parsec 解析器具有不同流类型的 Parsec 解析器?