传递道具到反应还原容器组件

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

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

示例容器组件代码:

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 状态对象上,也不希望将道具传递给表示组件。

有没有办法把道具传给这个容器组件?或者,有没有其他我忽略的方法?

谢谢。

56607 次浏览

You can pass in a second argument to mapStateToProps(state, ownProps) which will give you access to the props passed into the component in mapStateToProps

mapStateToProps and mapDispatchToProps both take ownProps as the second argument.

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

For reference

Using Decorators (@)

If you are using decorators, the code below give an example in the case you want to use decorators for your redux connect.

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

If you now check this.props.Foo you will see the prop that was added from where the Bar component was used.

<Bar Foo={'Baz'} />

In this case this.props.Foo will be the string 'Baz'

Hope this clarifies some things.

There's a few gotchas when doing this with typescript, so here's an example.

One gotcha was when you are only using dispatchToProps (and not mapping any state props), it's important to not omit the state param, (it can be named with an underscore prefix).

Another gotcha was that the ownProps param had to be typed using an interface containing only the passed props - this can be achieved by splitting your props interface into two interfaces, e.g.

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);

The component can be declared by passing the single parameter:

<MyComponent value={event} />