React Navigation 5 headerRight button函数调用不会获取更新状态

问题描述 投票:0回答:1

在下面的简化示例中,用户使用TextInput更新标签状态,然后单击标题中的“保存”按钮。在Submit函数中,当请求标签状态时,它返回原始值”,而不是更新后的值。

需要对导航标题右按钮进行哪些更改才能解决此问题?

注意:当“保存”按钮在渲染视图中时,所有内容均按预期方式工作,而不是位于标题中时。

import React, {useState, useLayoutEffect} from 'react';
import { TouchableWithoutFeedback, View, Text, TextInput } from 'react-native';

export default function EditScreen({navigation}){
  const [label, setLabel] = useState('');

  useLayoutEffect(() => {
      navigation.setOptions({
        headerRight: () => (
          <TouchableWithoutFeedback onPress={submit}>
            <Text>Save</Text>
          </TouchableWithoutFeedback>
        ),
      });
    }, [navigation]);

  const submit = () => {
    //label doesn't return the updated state here
    const data = {label: label}
    fetch(....)
  }

  return(
    <View>
      <TextInput onChangeText={(text) => setLabel(text) } value={label} />  
    </View>
  )

}
react-native react-navigation react-navigation-v5
1个回答
0
投票

标签应作为useLayouteffect的依赖项传递,这将使挂钩在更改时运行

  React.useLayoutEffect(() => {
      navigation.setOptions({
        headerRight: () => (
          <TouchableWithoutFeedback onPress={submit}>
            <Text>Save</Text>
          </TouchableWithoutFeedback>
        ),
      });
    }, [navigation,label]);
© www.soinside.com 2019 - 2024. All rights reserved.