【发布时间】:2017-02-22 16:49:32
【问题描述】:
我是 React Native 的新手。我正在为我的 react native 应用程序使用 redux 架构,但是由于 redux 的全局存储状态,我遇到了问题。
返回导航时,
根据 redux 架构,它将导航堆栈中存在的每个页面实例的状态更改为商店中的最新状态。
这是上面例子的代码,
Page.js [组件]
class Page extends Component{
componentWillMount(){
}
render(){
var {image,apiCall} = this.props;
return (
<View>
<Image Source={{uri:image}} style={{// style for the image}}>
</View>
)}
componentDidMount(){
this.props.apiCall(this.props.route.data.link); // this.props.route.data.link -> this is just a link for // the apiCall
}
componentWillReceiveProps(){
}
shouldComponentUpdate(nextProps, nextState){
if(this.props.image==nextProps.image){
return false;
}
return true;
}
componentWillUpdate(){
}
componentDidUpdate(){
}
componentWillUnmount(){
}
}
const mapStateToProps = (state) => {
return {
image: state.PageDataReducer.image
};
};
const mapDispatchToProps = (dispatch) => {
return {
apiCall: (link) => {
dispatch(fetchProduct(link)); // fetchProduct() -> is a function which fetches the product from the // network and dispatches the action.
},
};
};
export default connect(mapStateToProps,mapDispatchToProps)(Page);
fetchProduct() [获取产品的函数]
export function fetchProduct(link) {
return function(dispatch){
// fetches the product over network
dispatch(fetchedProduct(productLink));
}
}
fetchedProduct [操作]
export const fetchedProduct = (productLink) => {
return {
type: FETCHED_PRODUCT,
image: image
};
};
PageDataReducer [Reducer]
export default function PageDataReducer(state = initialState, action) {
switch (action.type) {
case FETCHED_PRODUCT:
var newState = {
...state,
image: action.image
};
return newState;
default:
return state;
}
}
我的观察:每当导航中出现相同的页面并且该页面的商店中的状态发生变化时,它就会调用该页面的 mapStateToProps() 该页面的次数位于导航堆栈中。因此,它循环通过该页面的生命周期方法以根据最新状态更改状态的次数。
在此示例中,当我单击香蕉时 在抽屉中,它将商店中的状态从芒果更改为香蕉,并且 mapStateToProps() 被调用 3 次(因为该页面在导航堆栈中出现了 3 次) 因此从 componentWillReceiveProps() 到 componentDidUpdate() 的所有响应生命周期方法都被调用了 3 次,只是为了根据最新状态更改该页面的状态。
我想要什么:我想要导航中页面的不同状态,以便在返回时可以看到我访问过的所有不同产品。
根据 redux 架构,问题很明显,但我没有解决它的窍门。为实现我的目标而提供的任何帮助或任何其他工作将不胜感激。
【问题讨论】:
-
你能澄清你的问题吗?
-
@DamienLeroux,是的,我已经在上面编辑了我的问题。你能再看一遍吗?
-
您说“根据 redux 架构,它正在将导航堆栈中存在的每个页面实例的状态更改为商店中的最新状态。”如果没有将每个应用程序状态保存在某处的代码,redux 架构就不会这样做。可能是你的问题
标签: android reactjs react-native redux react-router