【发布时间】:2020-09-25 22:39:08
【问题描述】:
我正在使用自定义的useLocalStorage 钩子定义:
import { useState } from 'react';
// Hook
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = value => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;
在我的主应用程序中,我有一个搜索栏和一个列表组件,我想将用户写入本地存储的任何内容添加到搜索栏下方,这就是我尝试做的事情:
function App() {
const [data, changeData] = useLocalStorage('data', []);
return {
<div className="App">
<SearchBar changeData={changeData} data={data}> </SearchBar>
<ListComp data={data}> </ListComp>
</div>
}
而 ListComp 看起来像这样:
class ListComp extends React.Component {
render() {
const { data } = this.props;
return data.map(
city => <p key={city}> {city} </p>
)
}
}
export default ListComp
SearchBar 看起来像这样:
import { Input } from 'antd'
function SearchBar(props) {
const { Search } = Input
const { changeData, data } = props
return (
<>
<div>
<Search
type="text"
placeholder="Enter a city name"
onSearch={(e) => {
data.push(e)
changeData(data)
}}
/>
</div>
</>
);
}
export default SearchBar;
问题是,虽然 localStorage 确实更新了,但我的组件似乎没有更新,而且我一按下按钮就无法在屏幕上看到更新的列表 - 我需要刷新才能看到它更新。
有人知道我做错了什么吗?我很新的反应和尝试学习它,所以我很想得到一些帮助!
谢谢:)
【问题讨论】:
-
你在
changeData之后的App组件中试过控制台data
标签: javascript reactjs react-hooks local-storage