如何让React在道具改变时重新渲染一个功能组件



在我的应用程序中,我将一些天气数据作为道具传递给组件,我希望根据该值更新温度的颜色。这就是我所做的。当道具改变时,react并不总是重新渲染。我怎样才能确保每次道具改变时都会更新这个?

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>
)

}这里e

您在这里混淆了几个概念,这破坏了实现。一方面,您将天气对象(带有颜色)作为道具传递,但您也在本地状态中存储/引用它,并使用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} />