首页 > 解决方案 > React Native - 孩子的状态发生了变化,如何更新父母?

问题描述

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

我还使用反应导航从我的父屏幕转到子屏幕。

这是我的代码:

父屏幕:

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

子屏幕:

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>

)}

如果父组件中的帖子 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();
  }, []);

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

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

  const { user } = useAuth();

  return (
    <React.Fragment>
      <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)}
          />
        )}
      />
      <PostDetailsScreen addToLikes={addToLikes(posts.id, user.id)} />
    </React.Fragment>
  );
}

子屏幕:

function PostDetailsScreen({ route, addedToLikes, addToLikes }) {
  const post = route.params;

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

  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 (
    <React.Fragment>
      <TouchableOpacity
        onPress={() => {
          addToLikes;
        }}
      >
        {addedToLikes ? <MaterialCommunityIcons name="heart" /> : <MaterialCommunityIcons name="heart-outline" />}
      </TouchableOpacity>

      <View>
        <TextInput>{show_likes}</TextInput>
      </View>
    </React.Fragment>
  );
}

标签: react-native

解决方案


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

听起来你有这样的结构:

父母(不知道likes)-> 孩子(知道likes

但是你想要这样的东西:

父母(知道likes) -> 孩子(与 互动likes

因此,我建议让您state在 Parent 组件中跟踪isLikedlikesCount. 父组件还会将方法处理程序传递给子组件,例如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;

推荐阅读