【问题标题】:Is it possible to trigger a Redux action from outside a component? [duplicate]是否可以从组件外部触发 Redux 操作? [复制]
【发布时间】:2018-11-30 10:30:11
【问题描述】:

我正在构建一个 React 应用程序并调用一个自定义处理程序库来调用我们的 REST API。

在这些(非 React)函数中,我想触发 Redux 操作以使用端点响应更新存储,但不知道如何在没有通常的 'mapDispatchToProps'/connect( ) 方法。

这可能吗?

谢谢

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    为了从React.Component 的范围之外进行调度和操作,您需要获取商店实例并在其上调用dispatch,就像

    import { store } from '/path/to/createdStore';
    ​
    function testAction(text) {
      return {
        type: 'TEST_ACTION',
        text
      }
    }
    ​
    store.dispatch(testAction('StackOverflow'));
    

    【讨论】:

    • 这是否也适用于原生反应?
    • @ManuelHernandez 是的,它也适用于 react-native
    • 这是反模式?还是应该使用?
    • 是否已弃用商店发货?我正在导入商店,但其中没有调度...
    • 这项工作将于 2020 年 3 月 19 日生效
    【解决方案2】:

    我真的很喜欢复制 Promise 使用的 resolve/reject 或 onSuccess/onError 模式。

    所以我建议你做同样的事情。您调用自定义处理程序并将 onSuccess 和 onError 回调传递给它。因此,当您获取数据时,您可以调用 onSuccess,如果出现错误,您可以调用 onError 回调。

    onSuccess 和 onError 是您将在组件中拥有的函数,它们将向用户显示某些内容或执行其他操作(在出现错误时显示错误 toast 消息?!)。

    让我们看一个例子:

    export default class CustomService{
        getData(onSuccess, onError){
            //axios.get(...) or fetch(...)
            if(success) call onSuccess(result)
            if(error) call onError(error)
        }
    }
    
    export default class MyComponent extends React.Component{
       constructor(props){
           super(props);
    
           this.state = {
               showError:false
           }
    
           this.customService = new CustomService();
    
           this.onSuccess = this.onSuccess.bind(this);
           this.onError = this.onError.bind(this);
       }
    
       componentDidMount(){
           this.customService.getData(this.onSuccess, this.onError);
       }
    
       onSuccess(result){
           // Do something if necessary
           // Call the redux action
       }
    
       onError(error){
           //Show a toast message to user or do something else
           this.setState({showError:true});
       }
    }
    

    在 onSuccess 中你可以调用 Redux 来存储你的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2012-11-08
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      相关资源
      最近更新 更多