我正在通過子組件中的回呼更新背景關系中的共享狀態,但這不會導致重新渲染,這會導致子組件中的背景關系在下一次重新渲染之前具有初始值。
一旦在背景關系提供程式中更新狀態,有沒有辦法強制更新子項并重新渲染?
我的背景關系提供者:
const UserLocationContext = React.createContext()
export const useUserLocation = () => {
return useContext(UserLocationContext)
}
export const UserLocationProvider = ({ children }) => {
const [ipUserLocation, setIpUserLocation] = useState(null)
const updateIpUserLocation = (ipUserLocation) => {
setIpUserLocation(ipUserLocation)
console.log(ipUserLocation) //value is updated here immediately after the updateIpUserLocation call
}
return (
<UserLocationContext.Provider value = {{ipUserLocation, updateIpUserLocation}}>
{children}
</UserLocationContext.Provider>
)
}
export default UserLocationProvider
孩子:
const LocationHandler = () => {
const {ipUserLocation, updateIpUserLocation} = useUserLocation()
useEffect(() => {
const ip_url = `https://api.freegeoip.app/json/`
const fetchIPLocation = async () => {
const result = await fetch(ip_url);
const json = await result.json();
updateIpUserLocation([json.latitude, json.longitude])
console.log(ipUserLocation) //value here remains null until next re-render
}
fetchIPLocation()
}, []);}
uj5u.com熱心網友回復:
問題是useState異步的,因此在被呼叫ipUserLocation后不會立即更新值。setIpUserLocation
對于修復,您可以將其添加ipUserLocation為依賴項useEffect,以幫助您收聽來自ipUserLocationon的所有更改LocationHandler。
const LocationHandler = () => {
const {ipUserLocation, updateIpUserLocation} = useUserLocation()
useEffect(() => {
const ip_url = `https://api.freegeoip.app/json/`
const fetchIPLocation = async () => {
const result = await fetch(ip_url);
const json = await result.json();
updateIpUserLocation([json.latitude, json.longitude])
}
fetchIPLocation()
}, []);}
//add another `useEffect` with `ipUserLocation` in dependencies
useEffect(() => {
//TODO: You can do something with updated `ipUserLocation` here
console.log(ipUserLocation)
}, [ipUserLocation])
return ...
}
uj5u.com熱心網友回復:
實際上,當您更新背景關系的狀態時,子組件會重新渲染。發生這種情況是因為您正在使用useContext掛鉤來偵聽對背景關系所做的任何更改。你可以做的是向自己證明孩子被重新渲染是在子組件中添加這個:
useEffect(() => {
console.log(ipUserLocation);
}, [ipUserLocation])
有了這個 useEffect,console.log將在每次重新渲染孩子并且ipUserLocation發生變化時運行。
檔案:https ://reactjs.org/docs/hooks-effect.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460665.html
標籤:javascript 反应 反应上下文
