首页 > 解决方案 > 不支持在使​​用 componentWillMount 或 componentWillUnMount 时动态更改 `store`

问题描述

不支持store即时更改。您很可能会看到此错误,因为您更新到 Redux 2.x 和 React Redux 2.x,它们不再自动热重载减速器

当我使用 componentWillMount 和 componentWillUnMount 我得到这个错误

import React, { Component } from 'react';
import { View, NetInfo, Image } from 'react-native';
import { Container, Text } from 'native-base';
import { RootNavigator } from './src/root';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import resducers from './src/reducers/index';

export default class App extends Component<Props> {
  constructor(Props){
    super(Props);
    this.state={
      connection:null,
    }
  }

  componentWillMount(){
    NetInfo.isConnected.addEventListener("connectionChange",this.handleConnectionChange);
    NetInfo.isConnected.fetch().done((isConnected)=>this.setState({connection:isConnected}));
  }

  componentWillUnMount(){
    NetInfo.isConnected.removeEventListener("connectionChange",this.handleConnectionChange);
  }

  handleConnectionChange=(isConnected)=>{
    this.setState({connection:isConnected});
  }

  handeView(){
    if(this.state.connection!==null && this.state.connection){
      return <RootNavigator />
    }else {
      return <View style={{flex:1, flexDirection:"row", alignItems:"center", justifyContent:"center"}}>
         <Image source={require("./images/connection.gif")} style={{height: 150, width: 150, resizeMode : "stretch"}}/>
      </View>
    }
  }

  render() {
    return (
      <Provider store={createStore(resducers)}>
         <Container>
             {this.handeView()}
         </Container>
      </Provider>
    );
  }
}

标签: javascriptreact-nativereduxreact-reduxredux-thunk

解决方案


每次您的组件呈现时,都会创建一个新的商店。尝试在组件之外创建商店。

import resducers from './src/reducers/index';    
const store = createStore(resducers);

--

<Provider store={store}>

推荐阅读