React Native - Redux:app中相同状态的多个实例

Kal*_*kar 7 android reactjs react-router react-native redux

我是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);
Run Code Online (Sandbox Code Playgroud)

fetchProduct()[获取产品的函数]

export function fetchProduct(link) {
  return function(dispatch){
    // fetches the product over network
    dispatch(fetchedProduct(productLink));
  }
}
Run Code Online (Sandbox Code Playgroud)

fetchedProduct [动作]

export const fetchedProduct = (productLink) => {  
  return {
    type: FETCHED_PRODUCT,
    image: image
  };
};
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的观察:每当导航中出现相同的页面并且该页面的存储中的状态发生变化时,它就会调用该页面的mapStateToProps()页面在导航堆栈中的次数.因此,它循环遍历该页面的生命周期方法以根据最新状态更改状态.
在这个例子中,当我点击抽屉中的香蕉时,它在商店中将状态从芒果更改为香蕉,并且mapStateToProps()被调用3次(因为该页面在导航堆栈中存在3次)因此所有从componentWillReceiveProps()到componentDidUpdate()的生命周期反应方法被调用3次,只是为了根据最新状态更改该页面的状态.

我想要的是:我希望导航中页面的状态不同,所以回过头来我可以看到我访问过的所有不同的产品.

根据redux架构,问题很明显,但我没有得到解决它的技巧.任何帮助或任何其他工作来实现我的目标将不胜感激.

Dam*_*oux -1

你想要做的事情不能只用 Redux 来完成。

您需要在浏览器或应用程序中记录导航更改时的更改。HistoryJS就是用来做到这一点的。React-router使用此模块在 Web 导航中提供良好的用户体验。

因此,要么使用react-router声明不同的页面(每种水果一个),要么至少使用HistoryJS以编程方式保存导航状态。

我不知道react-router如何对本机应用程序做出反应,所以看看React Native Router它提供了一种在本机应用程序上使用 Redux 处理导航的方法。