简体   繁体   English

如何在 Redux 状态更新时更新功能组件?

[英]How to get a functional component to update when Redux state gets updated?

I fetch user's data (including profile picture) using Redux.我使用 Redux 获取用户的数据(包括个人资料图片)。 Sometimes the user changes his profile picture, redux updates it well but the update only appears when I restart the app.有时用户会更改他的个人资料图片,redux 会对其进行很好的更新,但只有在我重新启动应用程序时才会出现更新。 I want it to update automatically once the user uploads a new photo.我希望它在用户上传新照片后自动更新。 I don't know how can I do that?我不知道我该怎么做? Is it a problem in the profile picture component or the way I fetch data using Redux.是个人资料图片组件有问题还是我使用 Redux 获取数据的方式有问题。

here's how I fetch user's data:这是我获取用户数据的方式:

export function fetchUser() {
  return (dispatch) => {
    firebase
      .firestore()
      .collection('users')
      .doc(firebase.auth().currentUser.uid)
      .get()
      .then((snapshot) => {
        if (snapshot.exists) {
          dispatch({ type: USER_STATE_CHANGE, currentUser: snapshot.data() });
        } else {
          console.log('does not exist');
        }
      });
  };
}

and here's the profile picture component (which I want to update every time the user updates his photo):这是个人资料图片组件(我想在用户每次更新他的照片时更新):

function DrawerProfilePicture(props) {

  const [image, setImage] = useState(null);

const { currentUser } = props;    
useEffect(() => {
      setImage(currentUser?.pp);
  }, [currentUser?.pp]);

  if (!currentUser) {
    return (
      <View>
      </View>
    );
  }

  return (

      {!image ? (
        <Image
          style={{ width: 100, height: 100 }}
          source={require('../../assets/default.png')}
        />
      ) : (
        <Avatar.Image size={100} source={{ uri: image }} />
      )}
  );
}

const mapStateToProps = (store) => ({
  currentUser: store.userState.currentUser,
});
export default connect(mapStateToProps, null)(DrawerProfilePicture);
const { currentUser } = props;    
useEffect(() => {
      setImage(currentUser.pp);
  }, [currentUser.pp]);

The problem when you use empty brackets [] its update state only once when component rendered, when you add parameters it will re-render each time this parameter updated问题当您使用空括号 [] 时,组件渲染时其更新状态仅更新一次,当您添加参数时,每次更新此参数时都会重新渲染

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM