我可以将.getState()方法作为道具传递给我的组件吗

Can I pass the .getState() method in as a prop to my components?

本文关键字:我的 组件 getState 方法 我可以      更新时间:2023-09-26

我可以将dispatch作为容器的道具进行修补。我还可以将状态对象的副本传递给我的容器。然而,我想做的是将方法"getState()"作为this.props.getState.传递给我的容器

有办法做到这一点吗?


为什么我想这样做:

我的应用程序的结构相当大,为了简化,我试图将任何实际上不需要在单独文件("实用程序"文件夹)中的容器中的逻辑排除在外。例如,我们有一个自定义后端,因此所有处理从后端发送和接收的代码都位于/实用程序/api.js

现在,为了让这些实用程序能够访问存储,我一直在从..导入存储/store/createStore.js。这运行得很好,但我想做的是使用依赖注入从调用api的组件传递dispatch和getState,这样就更容易为这些应用程序编写单元测试,并提高我们未来可能开发的其他Redux应用程序的模块性。

本质上,我想写的是这样的东西:

//(Pesudocode)
// ../containers/SomeComponent.js
import api from '../utilities/api'
class SomeComponent extends Component {
  constructor(props){
    super(props);
    this.api = api(this.props.dispatch, this.props.getState);
}
someMethod(){
  this.api.foo('bar');
}
// etc. 
// pseudocode
// in ../utilities/api.js
export default function(dispatch, getState){
  return {
    foo: function (bar){
      // dispatch a complicated action which changes the state considerably
       dispatch(action.someAction(bar))
      // get the new state. 
       console.log("New State", getState());
    }
    baz: function (razz, dugi){
      // do something else
    }
  }

我发现,当类被构造时,可以发送当前状态的副本,但我确实需要函数getState()来调用,因为其中一些函数是异步的。

可能还有其他模式,比如使用异步操作,但就我们所做的而言,它运行良好。

这可以使用React的上下文来解决,它本质上是一种依赖注入机制,允许您在组件树的任意级别发送类似于prop的值。

如果您使用Redux或类似的状态容器:,它的实现看起来是这样的

const store;
class App extends Component {
    static childContextTypes: {
        getState: React.PropTypes.func.isRequired
    }
    
    getChildContext() {
        return {
            getState: () => store.getState()
        }
    }
    render() {
        return <ChildComponent/>
    }
}
class ChildComponent extends Component {
    constructor(props, context) {
        super(props, context);
        this.api = api(props, context.getState);
    }
    
    static contextTypes: {
        getState: React.PropTypes.func.isRequired
    }
}

您要做的是重新创建连接组件。connect()调用中的mapStateToProps参数所做的是从存储中提取选定的状态,并将其附加为道具。我不建议这样做,但你可以把整个州作为一个论点。

退一步看一下你正在尝试做什么,你似乎可以使用redux-thunk库,并围绕你的api创建一个包装器动作创建者,看起来像这样。

const apiAction = (url, onComplete) => {
    return (dispatch, getState) =>
        const state = getState();
        ...some logic
        api(foo, bar, onComplete)
}

您当前正在用您的api调用包装redux操作创建者,而您应该用redux操作生成器包装您的api呼叫。