React Native -将setState函数作为属性传递以刷新屏幕

pftdvrlh  于 2023-01-21  发布在  React
关注(0)|答案(1)|浏览(130)

我是React Native的新手(使用Expo Go),我尝试使用navigate.navigate()将 prop 从配置文件屏幕传递到编辑配置文件屏幕。然后我想导航回配置文件屏幕,并希望刷新它,使其具有更新的信息。它没有刷新,配置文件屏幕中的状态也没有更新。以下是代码片段。
Profile.js

const Profile = () => {
 const [name, setName] = useState(‘’)
 let navigation = useNavigate();
 navigation.navigate(“Edit”, {name: setName};
 return ( <div>{name}</div> )
}

Edit.js

const Edit = ({ setName }) => {
 let navigation = useNavigate()
 let newName = “John”;
 setName(newName); // does not update name in Profile
 navigatiom.navigate(“Profile”) // does not update profile
}
esyap4oy

esyap4oy1#

你不能直接改变状态,你必须按照导航route,见下面的代码:
Profile.js

const Profile = () => {
  const [name, setName] = useState("");
  let navigation = useNavigation();

  const onPress = () => {
    navigation.navigate('Second', { updateName: (x)=>setName(x) }); //<---here you have to pass callback function
  };
  return (
    <View style={{ flex: 1 }}>
      <Button
        onPress={onPress}
        title="Add title here"
        color="#841584"
        disabled={false}
      />
      <Text>{name}</Text>
    </View>
  );
};

Edit.js

const Edit = ({ route }) => {  //<------here need to take route 
  let navigation = useNavigation();
  const onPress = () => {
    let newName = "John";
    route.params.updateName(newName);   //<-----this way to update.
    navigation.navigate("Home");
  };
  return (
    <View style={{ flex: 1 }}>
      <Button
        onPress={onPress}
        title="Add title here"
        color="#841584"
        disabled={false}
      />
      <Text>{"name"}</Text>
    </View>
  );
};

相关问题