0

在我的应用程序中,我将一些天气数据作为道具传递给组件,并且我希望根据该值获得临时更新的颜色。这就是我所做的。似乎当道具改变时反应并不总是重新渲染。我如何确保每次道具更改时都会更新?

const Current = (props) => {

const { weather } = props

const [color, setColor] = useState([])

useEffect(() => {
    setColor(tempScheme[weather.current.temp_f])
}, [weather, color])

return (
    <Container>
        <CardContent>
            <Header>
                <Typography variant='h6'>Currently</Typography>
                <Typography variant='h6'> {formatDate(props.weather.location.localtime)} </Typography>
            </Header>
            <Weather>
                <Typography variant='h5'> {props.weather.current.condition.text} </Typography>
                <Typography variant='h2' style={{"color": `rgb(${color})`}}> {Math.round(props.weather.current.temp_f)}&deg; </Typography>
            </Weather>
            <Location>
                <Typography variant='body1'> {props.weather.location.name}, {props.weather.location.region}</Typography>
                <Image src={props.weather.current.condition.icon} />
            </Location>
        </CardContent>
    </Container>
)

}这里

4

1 回答 1

0

您在这里混淆了一些概念,这破坏了实现。一方面,您将天气对象(带有颜色)作为道具传递,但您也在本地状态中存储/引用它,并使用 useEffect 设置此颜色的内部实例。换句话说,您不会对来自父组件的颜色更改做出反应。此外,如果父组件中的对象上的键/值发生更改,react 不会重新渲染,仅当对象本身发生更改时。您要做的是将颜色状态和 useEffect 上移一级,并调整 useEffect 的依赖数组,使其订阅正确的更改,所以

const [color, setColor] = useState(tempScheme[weather.current.temp_f] 

useEffect(() => {
 setColor(tempScheme[weather.current.temp_f])
}, [weather.current.temp_f])

然后将其作为颜色道具传递给孩子

<Current color={color} />

然后要在组件本身内消费,你可以这样做

const current = ({ color }) => ...restOfTheComponent 

或者,您可以通过删除本地状态和使用效果来简化这一点,并像这样直接传递颜色

<Current color={weather.current.temp_f} />
于 2021-09-08T13:02:43.007 回答