我是个新手,我不知道我用useEffect
号钩子有什么问题.代码编译成功,似乎一切正常.用户添加的组件显示在浏览器上并添加到localStorage
中,但刷新后,仅显示示例组件(框1),用户所做的输入将丢失.你知道问题出在哪里吗?
mport React, { Fragment, useState, useRef, useEffect } from 'react';
import { v4 as uuidv4} from 'uuid';
import { BoxList } from './components/BoxList';
import { SearchBox } from './components/SearchBox';
const KEY = "boxApp.boxes";
export function App() {
const [boxes, setBoxes] = useState([ {id: 1, title: 'Box 1', content: 'This is just an example of a box, remove it and create yours!' } ])
const boxTitleRef = useRef();
const boxContentRef = useRef();
useEffect(() => {
const storedBoxes = JSON.parse(localStorage.getItem(KEY));
if (storedBoxes) {
setBoxes(storedBoxes);
}
}, []);
useEffect(() =>{
localStorage.setItem(KEY, JSON.stringify(boxes));
}, [boxes]);
const removeBox = (id) => {
const remainingBoxes = boxes.filter((box) => box.id !== id);
setBoxes(remainingBoxes);
}
const addNewBox = (evt) => {
evt.preventDefault();
const boxTitle = boxTitleRef.current.value;
const boxContent = boxContentRef.current.value;
if (boxTitle === '' || boxContent === '') return;
setBoxes( previousBoxes => {
return ([...previousBoxes, { id: uuidv4(), title: boxTitle, content: boxContent}])
});
boxTitleRef.current.value = null;
boxContentRef.current.value = null;
}
return (
<Fragment>
<SearchBox />
<div>
<h2>Add a box</h2>
<form>
<input type='text' placeholder='Title' ref={boxTitleRef}></input>
<input type='text' placeholder='Content' ref={boxContentRef}></input>
<button type='submit' onClick={addNewBox}>➕</button>
</form>
</div>
<BoxList boxes={boxes} removeBox={removeBox}/>
</Fragment>
);
}
export default App;