问题描述
我在进行一些搜索后更新结果时遇到问题。它不会更新返回的输出。它第一次有效,但第二次没有更新结果。
这是我的代码:
我的代码:
const App = () => {
const[datas,setDatas] = useState([]) //for further process.
const [space,setSpace] = useState(null)
const [print,setPrint] = useState(false)
function getData(val){
console.log(val.target.value)
setSpace(val.target.value);
setPrint(false)
}
console.log(space) //Returning inputed text in console. Works well
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space //getting inputed text here
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts();
},[]);
return(
<div className="App">
{
print?
<>
<h2>{space}</h2> //submited text
<div>
{results.map((field) =>
<p>{field.title}</p>
<p>{field.author}</p>
)}
</div>
</>
:null
}
<input type="text" onChange={getData} />
<button onClick={() => setSpace(true)}>search</button>
</div>
)
}
};
export default App;
我不知道我错在哪里。请帮我解决这个问题...
解决方法
您只是在初始挂载时调用 useEffect。您必须注意 space
状态。
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space //getting inputed text here
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts();
},[space]);
通过在 useEffect 依赖列表中添加 space
状态,您可以重新获取新的结果。
您应该将 space
添加到 useEffect
依赖项数组,以确保每当 space
更新时效果都会运行。
但是——还有一个考虑因素。您可能最终会遇到竞争条件,即同时执行两个提取,或者在未安装的组件上设置状态。处理此问题的一种简单方法是维护效果执行是否属于当前安装的组件。您可以在 false
cleanup 函数中将此变量设置为 useEffect
。
useEffect(() => {
let isMounted = true;
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space //getting inputed text here
const res = await fetch(url);
const {result} = await res.json();
if (isMounted) setDatas(result);
}
fecthPosts();
return () => { isMounted = false };
},[space]);