【发布时间】:2019-06-25 18:25:42
【问题描述】:
我是 react-native 的新手,所以请善待。我的减速器正在更新,但我的组件生命周期没有被触发。我在组件中的 mapStateToProps 函数中有一个 console.log(),它为所有商店更新运行,但组件中没有发生任何事情
我的组件片段
class CompaniesComponent extends React.Component {
state = {refreshing: false}
static getDerivedStateFromProps (props, state) {
return {refreshing: props.data.loading};
}
onRefresh =() => {}
render () {
return (
<ScrollView bounces={false} refreshControl={<RefreshControl title="Loading..." refreshing={this.props.data.loading} onRefresh={()=>this.onRefresh()} /> } >
<Card>
<CardItem header bordered>
<Icon active name="business" />
<Text>Companies</Text>
</CardItem>
<List>
{this.renderComponentItems()}
</List>
</Card>
</ScrollView>
)
}}
const mapStateToProps = (state) => {
console.log("myState", state);
let data = state.api.data[constants.analytics.resources.profile];
console.log(data);
return { data }}
const mapMethodsToProps = {retrieveData, setCompany }
export default connect(mapStateToProps, mapMethodsToProps)(CompaniesComponent);
我的减速器
const apiReducer = (state=initialState, action) => {
switch(action.type) {
case actions.FETCH_DATA: {
let copy = Object.assign({}, state);
copy.data[action.payload.resource] = copy.data[action.payload.resource] || {};
copy.data[action.payload.resource]['loading'] = true;
return {
...copy
}
}
case actions.FETCH_DATA_FAILURE: {
let copy = Object.assign({}, state);
copy.data[action.payload.resource]['loading'] = false;
copy.data[action.payload.resource]['error'] = action.payload.error;
return {
...copy
}
}
case actions.FETCH_DATA_SUCCESS: {
let copy = Object.assign({},state);
copy.data[action.payload.resource]['loading'] = false;
copy.data[action.payload.resource]['data'] = action.payload.data;
return {
...copy
}
}
case actions.CLEAR_API_DATA: {
return {
...initialState
}
}
default: {
return state;
}
}}export default apiReducer;
【问题讨论】:
-
您还需要复制嵌套对象。有关说明,请参阅 Updating Nested Objects 的 Redux 文档。另请注意,您在 reducer 中不必要地复制了您的
state两次 - 首先是通过Object.assign,然后在您返回{ ...copy }时再次复制。 -
这是 100% 的收集答案!感谢您结束这一整天的噩梦。 !!!!
标签: reactjs react-native redux react-redux