gpt4 book ai didi

reactjs - 生命周期组件WillReceiveProps被多次调用

转载 作者:行者123 更新时间:2023-12-03 13:18:19 25 4
gpt4 key购买 nike

我一直在实现Tyler McGinnis curriculum学习 react 。

这是一个天气应用程序。而且我在调试奇怪的行为时遇到了麻烦。我很确定我正在做的事情很愚蠢,或者我可能错过了一些信息。

SearchContainer 是一个 ParentContainer,

var React = require("react");
var Search = require("../components/Search");

var SearchContainer = React.createClass({
propTypes: {
formType: React.PropTypes.string
},
contextTypes: {
router: React.PropTypes.object.isRequired
},
getDefaultProps: function() {
return {
formType: "form"
}
},
getInitialState: function() {
return {
city: ""
}
},
handleSearchSubmit: function(e) {
e.preventDefault();
this.context.router.push('/forecast/' + this.state.city);
},
handleCityChange: function(e) {
this.setState({
city: e.target.value
});
},
render() {
return (
<Search
formType={this.props.formType}
city={this.state.city}
onCityChange={this.handleCityChange}
onSearchSubmit={this.handleSearchSubmit}/>
);
}
})

module.exports = SearchContainer;

SearchContainer 更改上下文并切换到 ForecastContainer

var React = require("react");

var Forecast = require("../components/Forecast");
var Api = require("../helpers/Api");

var ForecastContainer = React.createClass({
getInitialState: function() {
return {
isLoading: true,
data: []
}
},
makeRequest: function(city) {
this.setState({
isLoading: true,
});
Api.getDayForecast(city).then( function(data) {
this.setState({
isLoading: false,
data: data.data.list
});
}.bind(this) );
},
componentDidMount: function() {
this.makeRequest(this.props.params.city);
},
componentWillReceiveProps: function(newProps) {
this.makeRequest(newProps.params.city);
},
render() {
return (
<Forecast isLoading={this.state.isLoading} data={this.state.data} />
)
}
});

module.exports = ForecastContainer;

现在,componentWillReceiveProps 被调用两次。我不明白为什么。从技术上讲,它应该只被调用一次。我正在 MakeRequest 方法中更新状态。状态改变后第二次调用。

我还附上了屏幕截图,以便更好地了解应用程序流程。

enter image description here

更新:

我使用的是 React-Router 版本 3.0.3。降级到 2.0.0 可以解决这个问题。更奇怪的是。

最佳答案

我无法告诉你为什么它被调用两次,但我可以告诉你这并不重要。问题是你没有比较 Prop 的变化。如果您这样做,代码将按照您想要的方式运行:

componentWillReceiveProps: function(newProps) {
if (newProps.params.city !== this.props.params.city) {
this.makeRequest(newProps.params.city);
}
},

另请参阅官方 ReactJS 文档,其中指出(强调我的): https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.

关于reactjs - 生命周期组件WillReceiveProps被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43316125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com