使用 react-redux 与 react-native 连接时的不变违规

Posted

技术标签:

【中文标题】使用 react-redux 与 react-native 连接时的不变违规【英文标题】:Invariant Violation when using react-redux connect with react-native 【发布时间】:2019-09-09 21:53:40 【问题描述】:

我开始构建一个 react-native 应用程序,我想在其中添加 redux。 我已经多次使用 redux 和 react-dom 并且从未遇到任何问题。现在使用 react-native 我无法使其工作。

我启动了一个非常简单的样板应用程序,但是当我将 connect HOC 添加到我的组件时,我遇到了以下错误:

这是我的组件的代码:

import React,  Component  from 'react';
import  Provider  from 'react-redux';
import  createStore, combineReducers  from 'redux';
import  connect  from 'react-redux';
import  View  from 'react-native';

const mainReducer = (state =  msg: 'Hello World!' , action) => 
    switch(action.type) 
        default: return state;
    
;

const store = createStore(combineReducers( mainReducer ));

class Main extends Component 
    render() 
        console.log('props: ', this.props);
        return (
            <View>this.props.msg</View>
        );
    


const MainWithRedux = connect(state => ( msg: state.msg ))(Main);
console.log('MainWithRedux: ', MainWithRedux);

export default class App extends Component 
    render() 
        return (
            <Provider store=store>
                <MainWithRedux />
            </Provider>
        );
    

从 console.log 我可以看到 connect hoc 确实返回了一个对象,而不是一个组件:

我使用 react-native-create-app 创建了我的项目,这些是我的依赖项:

"react": "16.6.3",
"react-native": "0.57.4",
"react-redux": "^7.0.2",
"redux": "^4.0.1"

我错过了什么吗?如何正确地将 react-redux 与 react-native 集成?

【问题讨论】:

【参考方案1】:

任何遇到这个问题的人,我相信这是因为react-nativereact-redux 版本。请参阅此以获取更多信息:https://github.com/reduxjs/react-redux/issues/1274

我在react-native@0.56.1react-redux@7.0.3 上遇到了这个错误。我目前无法升级我的react-native 版本,所以我不得不降级我的react-redux 版本。我将其降级为react-redux@5.0.6,现在一切似乎都正常了。

【讨论】:

【参考方案2】:

使用 connect 时,您没有指定需要从中导入“msg”的 reducer。

const MainWithRedux = connect(state => ( msg: state.mainReducer.msg ))(Main);

也许这可以解决您的问题。

【讨论】:

【参考方案3】:

只是把它扔在那里以防万一,因为我自己也在努力解决这个非常神秘的错误。我最终发现我是从 react-navigation 而不是 react-redux 导入 Provider 的。

【讨论】:

以上是关于使用 react-redux 与 react-native 连接时的不变违规的主要内容,如果未能解决你的问题,请参考以下文章

React-redux框架之connect()与Provider组件 用法讲解

使用 connect 与 react-redux 和 redux-persist

无法让 React-redux 与 redux-persist 一起使用

将 react-redux useSelector 与打字稿一起使用

React之react-redux的使用与项目的打包

redux与react-redux