【发布时间】:2021-01-04 17:08:50
【问题描述】:
我正在使用useContext 钩子来制作一个与其他组件共享状态的组件。
现在这个组件也在将状态保存到本地存储。
var initialState = {
avatar: '/static/uploads/profile-avatars/placeholder.jpg',
isRoutingVisible: false,
removeRoutingMachine: false,
markers: [],
currentMap: {}
};
var UserContext = React.createContext();
function setLocalStorage(key, value) {
function isJson(item) {
item = typeof item !== 'string' ? JSON.stringify(item) : item;
try {
item = JSON.parse(item);
} catch (e) {
return false;
}
if (typeof item === 'object' && item !== null) {
return true;
}
return false;
}
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (errors) {
// catch possible errors:
console.log(errors);
}
}
function getLocalStorage(key, initialValue) {
try {
const value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : initialValue;
} catch (e) {
return initialValue;
}
}
function UserProvider({ children }) {
const [user, setUser] = useState(() => getLocalStorage('user', initialState));
在我声明一些 useEffect 钩子之后:
const [
isLengthOfUserMarkersLessThanTwo,
setIsLengthOfUserMarkersLessThanTwo
] = useState(true);
useEffect(() => {
setLocalStorage('user', user);
}, [user]);
useEffect(() => {
console.log('user.isRoutingVisibile ', user.isRoutingVisibile);
}, [user.isRoutingVisibile]);
useEffect(() => {
console.log('user.markers.length ', user.markers.length);
if (user.markers.length === 2) {
setIsLengthOfUserMarkersLessThanTwo(false);
}
return () => {};
}, [JSON.stringify(user.markers)]
);
最后一个钩子是头刮,我在依赖项中传递一个数组,我想在数组长度达到 2 时做出反应(哈!)做一些事情。
当它到达那里时,我有一个 useState 钩子,它将改变变量的值。
const [
isLengthOfUserMarkersLessThanTwo,
setIsLengthOfUserMarkersLessThanTwo
] = useState(true);
我有一个函数,我想将它传递给另一个组件,该组件只能在三元返回 true 时触发。
现在,尽管数组的长度变为 2,setIsLengthOfUserMarkersLessThanTwo 并没有将变量更改为 false
return (
<UserContext.Provider
value={{
setUserMarkers: marker => {
console.log('marker ', marker);
console.log(
'isLengthOfUserMarkersLessThanTwo ',
isLengthOfUserMarkersLessThanTwo
);
isLengthOfUserMarkersLessThanTwo === true
? setUser(user => ({
...user,
markers: [...user.markers, marker]
}))
: () => null;
},
}}
>
{children}
</UserContext.Provider>
);
提前谢谢你!
【问题讨论】:
-
你能把它组合到一个codeandbox中吗?
-
最后一个useEffect也不需要返回noop函数
-
@AmirhosseinEbrahimi 这个应用程序使用了各种 API,所以它们无法工作,LMK 如果这个 link 工作。
-
它由于它的大小无法运行,但是我看到了你的源代码,并且你需要 useReducer,你可以看看这个更大的article。如果你愿意,我可以写一个关于如何使用 useReducer 进行转换的答案
-
我真的想通了我的朋友!
Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime!新年快乐!
标签: reactjs react-hooks use-context