我正在尝试将道具通过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>
);
}
}
答案 0 :(得分:3)
当您以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
包裹了Link
,
<button type="submit">
<Link
to={{
pathname: "/WeatherResult",
state: { temp1: this.state.temp1 }
}}
>
Submit
</Link>
</button>
使用temp1
函数提交表单后,您将在weatherSubmit
状态变量中获取数据。
因此,一旦您单击提交按钮,它将不会阻止执行以完成weatherSubmit
函数的执行,并且将直接导航到路径为"/WeatherResult"
的目标组件。因此,在这种情况下,您的weatherSubmit
函数未得到执行,并且您正在获取目标组件中状态的初始值,即undefined
(初始状态)。
解决方案是不要使用Link
包装按钮,将按钮保持简单
<button type="submit">
Submit
</button>
您可以在weatherSubmit
函数返回成功并且使用setState中的回调成功设置temp1
状态之后进行导航。
this.setState({
temp1: data.main.temp
}, () => this.props.history.push({
pathname: '/WeatherResult',
state: { temp1: JSON.stringify(this.state.temp1) }
}));