- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 componentDidMount
的机制有疑问。我正在构建一个天气应用程序,它使用外部 API 来获取城市的预报数据。
我的预测容器是这样构建的
var React = require('react');
var Forecast = require('../components/Forecast');
var weatherHelpers = require('../utils/weather');
var ForecastContainer = React.createClass({
getInitialState: function(){
return {
isLoading: true,
forecastData: {}
}
},
componentDidMount: function(){
weatherHelpers.getCityForecast(this.props.routeParams.city)
.then(function(results){
this.setState({
isLoading: false,
forecastData: results
})
}.bind(this))
},
render: function() {
return (
<Forecast
city={this.props.routeParams.city}
isLoading={this.state.isLoading}
forecastData={this.state.forecastData}
/>
)
}
});
module.exports = ForecastContainer;
我正在使用 axios 向天气 api 发送 http get 请求,并将该功能存储在名为 WeatherHelpers 的帮助程序文件中。
function Forecast(props) {
console.log(props)
return (
<div style={styles.container}>Forecast component</div>
)
}
当我从 Forecast 组件记录 props 时,它会被记录两次。一次为初始状态,一次为更新后的状态。这只是状态生命的运作吗:初始状态和 componentDidMount 内运行指令之间的滞后?是否重新渲染了我的组件(因此有两个控制台日志)。如果是这样,起作用的机制是什么?组件如何监听它的状态?
最佳答案
这是因为在生命周期中 render
在 componentDidMount
之前运行(请参阅 React documentation )。
顺序是:
constructor()
componentWillMount()
render()
componentDidMount()
当componentDidMount
运行时,render
已经运行。 componentDidMount
中的状态更改会触发另一个渲染。
编辑
我的旧答案(不正确,但现在已修改)如下,但还有其他需要记住的事情。如果您将 componentDidMount
更改为 componentWillMount
,它仍然会渲染两次,因为 promise :
weatherHelpers.getCityForecast(this.props.routeParams.city).then(...
当组件最初渲染时,componentWillMount
将运行,设置 Promise,然后渲染自身。然后 Promise 完成,更新状态,React 根据状态变化再次渲染。
关于Reactjs生命周期函数渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685921/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!