从提供者App.js反应本机调用操作

时间:2018-03-14 10:41:25

标签: react-native redux react-redux

我使用react native和redux作为以下(工作):

App.js

export default class App extends React.PureComponent {
  constructor (props) {
    super(props);

    this.state = { ...store.getState()};
    store.subscribe(() => {
      // i can read the state but no write it
      const storestate = store.getState();       
    });
  }

  handleConnectivityChange = isConnected => {
    this.setState({ isConnected });
  };

  render() {
    return (
      <Provider store={store}>
        <PersistGate
          loading={<ActivityIndicator />}
          persistor={persistor}>

          <View style={{ flex: 1, marginTop: Config.marginTop }}>
            <StackView />

          </View>
        </PersistGate>
      </Provider>
    );
  }
}

ScreenX.js

import * as actions from "./redux/actions";
import { connect } from "react-redux";

class ScreenX extends React.Component {
    ...
    // i can do in any fonction 
    this.props.action_saveNetInfo(isConnected);
    ...
}

function mapToStateProps(data) {
  return {
    isConnected: data["isConnected"] 
  };
}
export default connect(mapToStateProps, actions)(ScreenX);

当我从App.js以外的其他组件调用操作

时,redux存储工作很好

问题:

我想调用APP.js的行动,但这不会起作用

  handleConnectivityChange = isConnected => {
    this.props.action_saveNetInfo(isConnected);
  };

错误:TypeError: this.props.action_saveNetInfo is not a function

我也不能这样做

  class App extends React.PureComponent { ...   }

  export default connect(null, null)(App)

因为它会引发错误:

    Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(App)".

有什么想法吗? 感谢

2 个答案:

答案 0 :(得分:5)

在App组件中,您可以直接从dispatch拨打store。然后,您只需要发送您的actionCreator。

import {action_saveNetInfo} from './redux/actions'
// ...
handleConnectivityChange = isConnected => {
    store.dispatch(action_saveNetInfo(isConnected));
};

答案 1 :(得分:0)

使用mapDispatchToProps函数将操作绑定到this.props