为什么我的this.props.navigation.setParams不起作用?

时间:2017-11-03 10:29:59

标签: javascript react-native react-navigation

我在selectedStyleIds上设置我的整数数组。为什么我的this.props.navigaion.setParams不起作用?

  _setSelectedStyleIds = (selectedStyleIds) => {
    const action = NavigationActions.setParams({ 
        params: {selectedStyleIds},
        key: 'id-1509842157447-6' <- got this from console
    });
    this.props.navigation.dispatch(action);
    this.props.navigation.setParams({styleIds:selectedStyleIds});
    this.setState({selectedStyleIds});
  }

onCheck = ({selectedStyleIds}) => {
    console.log('onCheck');
    console.log(selectedStyleIds); <- [1,2,3,4,5]
    this.props._setSelectedStyleIds(selectedStyleIds);
    this.setState({selectedStyleIds}); <- working
}



_handleTagStylePress = () => {
    this.props.navigation.navigate('TagStyle', {onCheck: this.onCheck, selectedStyleIds: this.state.selectedStyleIds});
}
on onNavigatioOptions(仅用于调试)

onPress={() => {
          let {image, text, ..., selectedSeasonIds,
            gender, selectedSizeIds, selectedColorIds, selectedStyleIds,
            brand, ..., base64 } = navigation.state.params;
          console.log('onsave')
          console.log(navigation.state.params.selectedStyleIds) <<-- []  

我一直在检查这些行超过50次,但显然this.props.navigation.setParams({selectedStyleIds});无效。

设置状态和参数时,所有其他内容都没有问题,但只有selectedStyleIds不能设置为navigation.state.params

3 个答案:

答案 0 :(得分:4)

我遇到了类似的问题,关于在组件本身内设置导航栏的标题。

以下对我有用。

1)我定义了navigationOptions方法(反应导航的回调方法来设置导航属性)

当此方法运行时,您很可能无法访问设置导航器状态所需的属性,因此只需返回当前参数,这就是我所做的:

static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state;
    return params;
};

2)我在componentDidMount中实现了标题构造,设置了状态:

componentDidMount(){
    t = "The window title";
    this.props.navigation.setParams({title: t });
}

I think the same could be done in any user interface event, like the onPress, and can be applied to any property.

重要提示: 无效工作之间的区别是navigationOptions方法的定义,即使它是一个“无所事事”的方法(返回它得到的,不变的)

答案 1 :(得分:2)

现在,在2020年,react native的官方文档似乎建议您使用route.param来获取所需的参数。

        const { itemId } = route.params;

这是来自官方文档:

通过将参数作为第二个参数传递到对象中,将参数传递给路线。navigation.navigate函数:navigation.navigate('RouteName',{/ * params go here * /})

阅读屏幕组件中的参数:route.params。

https://reactnavigation.org/docs/params/

答案 2 :(得分:0)

你可以做如下操作

const handleCancelTransfer = useCallback(() => {
  navigation.dispatch((state) => {
    const routes = state.routes.filter((routeInStack) => routeInStack.name !== "TransferConfirmation");
    routes[routes.length - 1] = {
      ...routes[routes.length - 1],
      params: { keepFormData: true }
    }
    return CommonActions.reset({
      ...state,
      routes,
      index: routes.length - 1,
    })
  });
}, [navigation]);