React - 构造函数()和componentDidMount
问题描述:
我使用Redux来创建我的分页。我的问题是,在constructor
我运行了一个方法,将解析URL并检查是否有任何关于分页。然后它运行一个将数据放入我的商店的操作。这一切运行顺利。React - 构造函数()和componentDidMount
然后,我有componentDidMount
方法,当我运行另一个操作 - 获取数据。在那里我使用了我以前推过的道具。不幸的是,商店处于初始状态。
我(简化)代码:
class NewsList extends React.Component {
constructor(props) {
super(props);
this.profile = document.getElementById('articles').getAttribute('data-profile');
this.parseHash();
}
parseHash() {
/* Method for parsing navigation hash
---------------------------------------- */
const hash = window.location.hash.replace('#', '').split('&');
const data = {
page: 1,
offset: 0
};
// hash parsing
this.props.setPagination(data);
}
componentDidMount() {
this.loadNews();
// If I use
// setTimeout(() => { this.loadNews(); })
// it works, but I feel this is hack-ish
}
loadNews() {
this.props.update({
current: {page: this.props.NewsListReducer.current.page, offset: this.props.NewsListReducer.current.offset},
next: {page: this.props.NewsListReducer.next.page, offset: this.props.NewsListReducer.next.offset}
});
}
}
当我console.log(this.props.NewsListReducer)
,我越来越undefined
两个current
和next
对象,但是当我使用终极版DevTools,数据是存在的。我能做什么?
答
看起来有些地方存在某种异步性。你可能正在使用react-redux吧?我认为这个异步来自connect
ed组件,因为它使用setState
when the store state has changed。 setState
安排异步状态更新。
因此this.props.NewsListReducer
不是最新的componentDidMount()
。
我猜this.props.update
是一个会取消新闻的动作,对不对?为什么您需要从组件向它提供分页信息?例如。使用redux-thunk,您可以在分派操作之前访问商店状态。这可能是您阅读(最新)分页信息的机会。
E.g.
export function fetchNews() {
return (dispatch, getState) => {
getState().NewsListReducer.current.page; // Up to date
...
fetch(...).then(() =>
dispatch({...}));
}
}
Btw。不要打电话给你的国家*Reducer
可能是个好主意。它是管理国家的减速机,但减速机不是这种状态的一部分。
尝试将this.parseHash()移入componentWillMount() – jzm
这与@jzm相同。 'constructor'就像'componentWillMount()'的替代品。 –
纯粹的反应。但是对于redux,请参阅最后一个答案:http://stackoverflow.com/a/37703446/769083 – jzm