我正在使用 Zusstand 使用商店进行响应,在该商店中,我创建了一个计时器,该计时器使用setInterval()
函数每秒更新一次时间。
我在商店中创建它,希望将时间传递给各种子组件,同时保持时间从中心位置存储和共享。
我能够更新商店中的时间并成功记录它,但是当我将它传递给子组件时,它们并没有更新时间。如何传递更新的时间并导致每经过一秒重新渲染时间?我不想useEffect()
在子组件中使用 a 。
ZUSTAND 商店
import create from "zustand";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
import toObject from "dayjs/plugin/toObject";
dayjs.extend(toObject);
import timezone from "dayjs/plugin/timezone";
dayjs.extend(timezone);
import { IGlobalStyles} from "utils/types";
import { useEffect } from "react";
interface IStyles {
time?: any;
}
const timer = setInterval(function () {
const time = dayjs().format("hh:mm:ss A")
console.log("Time in store", time);
return(time)
}, 1000);
const useGlobalStyles = create<IStyles>((set) => ({
time: timer
})
);
export default useGlobalStyles;
CHILD COMPONENT(这是我要显示时间的地方)
import React from "react";
import {
StyleSheet,
TouchableOpacity,
Text,
Button,
View,
Dimensions,
} from "react-native";
import {
NavigationRouteContext,
useNavigation,
} from "@react-navigation/native";
import * as Shadows from "../../styles/shadows";
import useGlobalStyles from "stores/GlobalStyles";
interface IDateTime {}
export default function DateAndTime({}: IDateTime) {
//Access zustand store and retreive the current updated time
const time = useGlobalStyles((store) => store.time);
return (
<View style={[styles.container(window.width), styles.shadow]}>
{/*I want this text component to update time from react Zustand Store*/}
<Text>{time}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: (containerWidth: any) => ({
borderWidth: 1,
position: "absolute",
top: 30,
right: 25,
backgroundColor: "#FFFFFF",
justifyContent: "center",
//marginBottom: "5%",
// width: 422,
// height: 128,
width: containerWidth * 0.45,
height: "8%",
borderRadius: 10,
padding: 20,
}),
text: {
alignSelf: "flex-end",
alignItems: "center",
fontSize: 10,
color: "black",
fontWeight: "700",
height: 20,
textAlign: "center",
},
shadow: { ...Shadows.componentShadow },
});