ChatGPT解决这个技术问题 Extra ChatGPT

将 props 传递给 react-redux 容器组件

我有一个在 React Native Navigator 组件中创建的 react-redux 容器组件。我希望能够将导航器作为道具传递给此容器组件,以便在其展示组件内按下按钮后,它可以将对象推送到导航器堆栈上。

我想这样做,而不需要手写 react-redux 容器组件给我的所有样板代码(也不要错过 react-redux 在这里给我的所有优化)。

示例容器组件代码:

const mapStateToProps = (state) => {
    return {
        prop1: state.prop1,
        prop2: state.prop2
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onSearchPressed: (e) => {
            dispatch(submitSearch(navigator)) // This is where I want to use the injected navigator
        }
    }
}

const SearchViewContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(SearchView)

export default SearchViewContainer

而且我希望能够从我的导航器 renderScene 函数中调用这样的组件:

<SearchViewContainer navigator={navigator}/>

在上面的容器代码中,我需要能够从 mapDispatchToProps 函数中访问这个传递的道具。

我不想将导航器存储在 redux 状态对象上,也不想将道具传递给演示组件。

有没有办法可以将道具传递给这个容器组件?或者,有没有我忽略的替代方法?

谢谢。


Z
Zajn

mapStateToPropsmapDispatchToProps 都将 ownProps 作为第二个参数。

[mapStateToProps(state, [ownProps]): stateProps] (Function):
[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function):

对于reference


G
Gilad Artzi

您可以将第二个参数传递给 mapStateToProps(state, ownProps),这将使您能够访问传递给 mapStateToProps 组件的道具


我如何在 mapDispatchToProps 中访问它?
@Michael 以同样的方式,您可以使用第二个参数
D
Damian Green

使用 typescript 执行此操作时有一些问题,所以这里有一个示例。

一个问题是,当您只使用 dispatchToProps(而不映射任何 state props)时,重要的是不要省略 state 参数(它可以用下划线前缀命名)。

另一个问题是必须使用仅包含传递的道具的接口键入 ownProps 参数 - 这可以通过将道具接口拆分为两个接口来实现,例如

interface MyComponentOwnProps {
  value: number;
}

interface MyComponentConnectedProps {
  someAction: (x: number) => void;
}

export class MyComponent extends React.Component<
  MyComponentOwnProps & MyComponentConnectedProps
> {
....//  component logic
}

const mapStateToProps = (
  _state: AppState,
  ownProps: MyComponentOwnProps,
) => ({
  value: ownProps.value,
});

const mapDispatchToProps = {
  someAction,
};

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

可以通过传递单个参数来声明组件:

<MyComponent value={event} />

J
Joe Lloyd

使用装饰器 (@)

如果您正在使用装饰器,下面的代码给出了一个示例,说明您想为您的 redux 连接使用装饰器。

@connect(
    (state, ownProps) => {
        return {
            Foo: ownProps.Foo,
        }
    }
)
export default class Bar extends React.Component {

如果您现在检查 this.props.Foo,您将看到从使用 Bar 组件的位置添加的道具。

<Bar Foo={'Baz'} />

在这种情况下,this.props.Foo 将是字符串 'Baz'

希望这可以澄清一些事情。