我使用componentWillMount方法调用 Action 创建者,然后它被调用两次。看看下面的结果截图。
这是我的 Action 创建者:
export function fetchAdmin(){
return (dispatch)=>{
axios.get(`${Config.API_URL}/admin`,{
headers: { authorization: localStorage.getItem('token')}
})
.then(response => {
return dispatch({
type: FETCH_DATA,
payload: response.data
});
}
)
.catch(response => {
console.log(response);
});
}
}
这是我的 reducer :
import { FETCH_DATA } from '../actions/types';
export function admin(state= {}, action){
switch(action.type){
case FETCH_DATA:
return {...state, lists: action.payload };
default:
return { state, lists: 'YEY!'}
}
}
这是我的容器,也是我使用 componentWillMount 调用 Action 创建者的方式。
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import * as actions from 'actions/admin_action';
class Admin extends Component{
componentWillMount(){
this.props.fetchAdmin()
}
renderData(){
var lists = this.props.lists;
console.log(lists);
}
render(){
return(
<div>
{this.renderData()}
</div>
)
}
const mapStateToProps = (state) => {
return { lists: state.admin.lists };
}
export default connect(mapStateToProps, actions)(Admin);
从屏幕截图中我假设 render() 被调用两次。第一个调用转到默认操作创建者,因此结果是“YEY!”第二个是有效的。
有人可以向我解释为什么 componentWillMount 会这样执行吗?实际上在第一个渲染中我只想我的数组不是“YEY!”如何解决这个问题呢?谢谢。
最佳答案
这里没有问题!当你的组件第一次渲染时,它在逻辑 componentWillMount
完成之前就到达了渲染,所以:
首次渲染:在全局状态下的 lists
为默认值(等于 YEY!
)时渲染您的组件。
第二次渲染:当数据获取成功后,全局状态下的lists
中的reducer会随着获取到的数据发生变化,之后你的组件会检测到由于 mapStateToProps
从全局状态获取lists
而发生变化。
不用说,React 组件会在 propsChange 上重新渲染,这就是为什么有一个方法 componentWillReceiveProps
,以便您可以在每次 props 更改时添加一些逻辑(如果需要)。
此行为允许您处理等待数据获取的情况:
- 添加加载微调器。
- 渲染您的布局。
- 获取页面中呈现的其他组件。
关于javascript - 使用 componentWillMount 调度 Action 创建者被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689793/