【问题标题】:Possible to dispatch an action without connect?可以在没有连接的情况下分派一个动作吗?
【发布时间】:2019-02-18 20:10:12
【问题描述】:
export default class App extends Component {
...
  componentDidMount() {
    //registering event listener
    BackgroundGeolocation.on('location', this.onLocation, this.onError);
  }

  onLocation(location) {
   //wishing to dispatch an action to update variable in store
  }

  render() {
    return (
      <Provider store={store}>
        <AlertProvider>
          <MainNavigator screenProps={{ isConnected: this.state.isConnected }} />
        </AlertProvider>
      </Provider>
    );
  }
}

据我了解,我无法连接到此组件中的存储,因为我们只是在配置并将存储传递给 Provider。我怎么可能在我的onLocation 事件中调度一个动作?

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    您可以直接使用 store 对象进行调度。

    store.dispatch({type:"UPDATE_VARIABLE", payload:variable.value})
    

    如果你在其他一些组件中store对象不可用,从主组件中导出并导入到需要它的位置并使用上面的语句

    【讨论】:

    • 乐于助人。 :)
    • 你从哪里导入“商店”?
    • @Renoldus 来自'/redux-store'
    • 在哪里定义了 rootreducer 或 combineReducers 包装器,从这个文件导入导出的存储。
    【解决方案2】:

    您可以使用此代码并像这样在类中添加构造函数

      constructor(props) {
        super(props);
      }
    
      onLocation() {
        this.props.dispatch({type: GET_THINGS_REQUESTED, payload: value});
      }
    

    【讨论】:

      【解决方案3】:

      react-redux 有自己的钩子来调用它们

      const dispatch = useDispatch();
      const state = useSelector((state) => state);
      

      不要忘记导入它们

      import { useDispatch, useSelector } from 'react-redux';
      

      如果您编写 useDispatch,vs 代码将自动完成

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-03
        • 2016-08-28
        • 2016-09-14
        • 2019-01-14
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多