React native 反应本机-子系统中的状态已更改,如何更新父系统?

React native 反应本机-子系统中的状态已更改,如何更新父系统?,react-native,React Native,目前我正在更改子组件中的状态,现在我想更新我的父组件。最初,我将数据从父对象传递给子对象,然后在子对象中更改状态。当我这样做时,应用程序中不会发生任何事情,因为父应用程序仍然没有更新,但当我重新加载应用程序时,所做的更改会更新 我还使用react导航从父屏幕转到子屏幕 这是我的密码: 父屏幕: function PostsScreen({navigation}) { const [posts, setPosts] = useState([]); const [error, setError]

目前我正在更改子组件中的状态,现在我想更新我的父组件。最初,我将数据从父对象传递给子对象,然后在子对象中更改状态。当我这样做时,应用程序中不会发生任何事情,因为父应用程序仍然没有更新,但当我重新加载应用程序时,所做的更改会更新

我还使用react导航从父屏幕转到子屏幕

这是我的密码:

父屏幕:

function PostsScreen({navigation}) {

const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);

const loadPosts = async () => {
setLoading(true);
const response = await postsApi.getPosts();
setLoading(false);

if (!response.ok) return setError(true);

setError(false);
setPosts(response.data);
};

useEffect(() => {
loadPosts();
}, []);

return(
<ActivityIndicator visible={loading} />
<FlatList
      data={posts}
      keyExtractor={(post) => post.id.toString()}
      renderItem={({ item }) => (
        <Card
          title={item.title}
          subTitle={item.subTitle}
          onPress={() => 
          navigation.navigate(routes.POST_DETAILS,item)}
        />
      )}
    />
  );
  }
函数PostsScreen({navigation}){
const[posts,setPosts]=useState([]);
const[error,setError]=useState(false);
const[loading,setLoading]=useState(false);
const loadPosts=async()=>{
设置加载(真);
const response=wait postsApi.getPosts();
设置加载(假);
如果(!response.ok)返回setError(true);
设置错误(假);
设置柱(响应数据);
};
useffect(()=>{
装载柱();
}, []);
返回(
post.id.toString()}
renderItem={({item})=>(
导航。导航(路线。发布详细信息,项目)}
/>
)}
/>
);
}
子屏幕:

function PostDetailsScreen({ route }) {
const post = route.params;
const { user} = useAuth();

const [addedToLikes, setAddedToLikes] = useState(post.isLiked);
const[likesCount,setLikesCount]=useState(post.likesCount)

const addToLikes = (PostId,userId) => {
postsApi.likePost({PostId,userId});
setAddedToLikes(!addedToLikes);
};

let show_likes="";
if(addedToLikes){
show_likes=(likesCount >1)?(("Liked by you")+" and "+(likesCount - 1)+((likesCount ==2)?( " 
other"):(" others"))):("Liked by you");
}else if(likesCount >0){
show_likes=(likesCount ==1)?(likesCount+ " like"):(likesCount + " likes");
}

return(
<TouchableOpacity onPress={() => {addToLikes(post.id,user.id)}}>
              {addedToLikes?<MaterialCommunityIcons
              name="heart"
            />:<MaterialCommunityIcons
                name="heart-outline"
              />}
</TouchableOpacity>

<View><TextInput>{show_likes}</TextInput></View>

)}
函数PostDetailsScreen({route}){
const post=route.params;
const{user}=useAuth();
const[addedToLikes,setAddedToLikes]=useState(post.isLiked);
const[likescont,setlikescont]=useState(post.likescont)
const addToLikes=(PostId,userId)=>{
postsApi.likePost({PostId,userId});
setAddedToLikes(!addedToLikes);
};
让我们展示你喜欢的东西;
如果(添加的规则){
show_likes=(likescont>1)?((“被你喜欢”)+”和“+(likescont-1)+((likescont==2)?”
其他人:(“其他人”):(“你喜欢”);
}否则如果(如计数>0){
show_likes=(likescont==1)?(likescont+“like”):(likescont+“likes”);
}
返回(
{addToLikes(post.id,user.id)}>
{addedToLikes?:}
{show_likes}
)}
如果父组件中有一个post isLiked和likesCount,如何更新

另外,我没有使用Redux

更新

我试着做了下面的事情,但还是不断出错

父屏幕:

function PostsScreen({navigation}) {

const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);

const loadPosts = async () => {
setLoading(true);
const response = await postsApi.getPosts();
setLoading(false);

if (!response.ok) return setError(true);

setError(false);
setPosts(response.data);
};

useEffect(() => {
loadPosts();
}, []);

return(
<ActivityIndicator visible={loading} />
<FlatList
      data={posts}
      keyExtractor={(post) => post.id.toString()}
      renderItem={({ item }) => (
        <Card
          title={item.title}
          subTitle={item.subTitle}
          onPress={() => 
          navigation.navigate(routes.POST_DETAILS,item)}
        />
      )}
    />
  );
  }
函数PostsScreen({navigation}){
const[posts,setPosts]=useState([]);
const[error,setError]=useState(false);
const[loading,setLoading]=useState(false);
const loadPosts=async()=>{
设置加载(真);
const response=wait postsApi.getPosts();
设置加载(假);
如果(!response.ok)返回setError(true);
设置错误(假);
设置柱(响应数据);
};
useffect(()=>{
装载柱();
}, []);
const[addedToLikes,setAddedToLikes]=useState(post.isLiked);
const addToLikes=(PostId,userId)=>{
postsApi.likePost({PostId,userId});
setAddedToLikes(!addedToLikes);
};
const{user}=useAuth();
返回(
post.id.toString()}
renderItem={({item})=>(
导航。导航(routes.POST_详细信息,项目)}
/>
)}
/>
);
}
子屏幕:

function PostDetailsScreen({ route }) {
const post = route.params;
const { user} = useAuth();

const [addedToLikes, setAddedToLikes] = useState(post.isLiked);
const[likesCount,setLikesCount]=useState(post.likesCount)

const addToLikes = (PostId,userId) => {
postsApi.likePost({PostId,userId});
setAddedToLikes(!addedToLikes);
};

let show_likes="";
if(addedToLikes){
show_likes=(likesCount >1)?(("Liked by you")+" and "+(likesCount - 1)+((likesCount ==2)?( " 
other"):(" others"))):("Liked by you");
}else if(likesCount >0){
show_likes=(likesCount ==1)?(likesCount+ " like"):(likesCount + " likes");
}

return(
<TouchableOpacity onPress={() => {addToLikes(post.id,user.id)}}>
              {addedToLikes?<MaterialCommunityIcons
              name="heart"
            />:<MaterialCommunityIcons
                name="heart-outline"
              />}
</TouchableOpacity>

<View><TextInput>{show_likes}</TextInput></View>

)}
函数PostDetailsScreen({route,addedToLikes,addToLikes}){
const post=route.params;
const[likescont,setlikescont]=useState(post.likescont);
让我们展示你喜欢的东西;
如果(添加的规则){
展示你的爱好=
LikeCount>1
?“你喜欢”+“和”+(喜欢计数-1)+(喜欢计数==2?“其他”:“其他”)
:“你喜欢”;
}否则如果(如计数>0){
show_likes=likescont==1?likescont+“like”:likescont+“likes”;
}
返回(
{
addToLikes;
}}
>
{addedToLikes?:}
{show_likes}
);
}

在不使用某种形式的共享状态(如Redux)的情况下,实现所追求的结果的最佳方法是确定组件结构

听起来你的结构是这样的:

家长(不知道
喜欢什么
)->孩子(知道
喜欢什么

但你想要的是这样的东西:

家长(了解
喜欢的人
)->孩子(与
喜欢的人互动

因此,我建议让父组件中的
状态
跟踪
isLiked
likecount
。父组件还将向子组件传递方法处理程序,例如
addToLikes(post.id,user.id)

示例代码:

import React from 'react';

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: null
        }
    }

    handleCallback = (childData) =>{
        this.setState({data: childData})
    }

    render(){
        const {data} = this.state;
        return(
            <div>
                <Child parentCallback = {this.handleCallback}/>
                {data}
            </div>
        )
    }
}

class Child extends React.Component{
  
    onTrigger = (event) => {
        this.props.parentCallback("Data from child");
        event.preventDefault();
    }

    render(){
        return(
        <div>
            <form onSubmit = {this.onTrigger}>
                <input type = "submit" value = "Submit"/>
            </form>
        </div>
        )
    }
}

export default Parent;
从“React”导入React;
类父类扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
数据:空
}
}
handleCallback=(childData)=>{
this.setState({data:childData})
}
render(){
const{data}=this.state;
返回(
{data}
)
}
}
子类扩展了React.Component{
OnTigger=(事件)=>{
this.props.parentCallback(“来自子对象的数据”);
event.preventDefault();
}
render(){
返回(
)
}
}
导出默认父对象;

我尝试了一种解决方案,在父组件中添加了addedToLikes状态和addToLikes函数,但现在,当我试图喜欢addToLikes不是一个函数的帖子时,我不断收到一个错误。我也尝试过返回,但我也不断收到一个错误我无法在我的父母内部调用它不断给我一个错误请共享一个代码沙盒,显示您尝试了什么,并告诉我们您遇到了什么错误是的,请共享代码在这种情况下,可能与您使用“this”键盘有关。如果看不到代码,这些东西可能会非常混乱:)谢谢你不能在一个组件中同时返回两个元素/组件,所以我添加了一些
。我认为,你如何传递
addToLikes
也是一个问题。。。您正在调用该函数,并将结果向下传递。您希望传递函数,以便在单击时调用它:
{console.log('您需要