【问题标题】:<Provider> does not support changing `store` on the fly<Provider> 不支持动态更改`store`
【发布时间】:2016-12-21 17:12:52
【问题描述】:

我最近开始学习如何同时使用 React-Native 和 Redux。我在 IOS 模拟器中遇到了一个错误,我无法弄清楚如何修复,我想知道是否有人以前见过这个。

这是错误:

Provider 不支持动态更改存储。您很可能会看到此错误,因为您更新到 Redux 2.x 和 React Redux 2.x,它们不再自动热重载减速器。有关迁移说明,请参阅 https://github.com/reactjs/react-redux/releases/tag/v2.0.0

我点击了错误消息中提到的链接,但似乎需要我使用 Webpack。在引用 if(module.hot) 的链接中,尝试使用此解决方案时出现以下错误:

无法解析模块

所以我不确定从这里去哪里。到目前为止,我的项目非常小。我有我的index.ios.js,然后是一个包含组件文件夹、商店文件夹和减速器文件夹的应用程序文件夹。结构如下:

  • index.ios.js
  • 应用程序
    • 商店
      • index.js
    • 组件
      • index.js
    • 减速机
      • index.js

这是我的代码:

index.ios.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import {
  AppRegistry,  
  StyleSheet,
  Text,
  View
} from 'react-native';

import {configureStore} from './app/store';
import Main from './app/components/Main';

export default class introToRedux extends Component {
  render() {
    return (
      <Provider store={configureStore()}>
        <Main />
      </Provider>
    );
  }
}

AppRegistry.registerComponent('introToRedux', () => introToRedux);

components/Main.js

import React, { Component } from 'react';
import {connect} from 'react-redux';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

var Main = React.createClass({
    render(){
        return (
            <View>
                <Text>{this.props.text}</Text>
            </View>
        );
    }
});

var mapStateToText = (state) => {
    return {
        text: state.text
    }
}

module.exports = connect(mapStateToText)(Main);

reducer/index.js

module.exports = (state={}, action) => {
    switch (action.type) {
        default: 
            return state;
    }
}

store/index.js

import {createStore} from 'redux';
import reducer from '../reducer';

var defaultState = {
    text: "default text"
}

export var configureStore = (initialState=defaultState) => {
    return createStore(reducer, initialState);
}

对此的任何帮助都会很棒!

【问题讨论】:

    标签: javascript react-native redux


    【解决方案1】:

    为什么要导出configureStore()?你也可以

    const initialState = {
        text: "default text"
    }
    
    export default function reducer (state=initialState, action) {
        switch (action.type) {
            default: 
                return state;
        }
    }
    

    createStore() 应该执行一次。

    index.js

    // import stuff
    
    const store = createStore(reducer)
    
    class IntroToRedux extends Component {
      render() {
        return (
          <Provider store={store}>
            <Main />
          </Provider>
        );
      }
    }
    
    ReactDOM.render(IntroToRedux, document.getElementById('root'))
    

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 2016-10-17
      • 2018-11-03
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多