我想更新;{字}";在api调用中触发来自另一个组件的响应,嵌套三个组件"向下";单击";。我需要使用redux还是其他上下文方法有效?
我之前曾试图使用redux来实现这一点,但我无法获得";{字}";改变。我还试图将api调用移到存储中,但后来发现我无法执行任何响应。
function handleResponse(response) {
setResult(response.data[0]);
}
function handlePexelsResponse(response) {
setPhotos(response.data.photos);
}
function search() {
let apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
axios.get(apiUrl).then(handleResponse);
const pexelsApiKey = `563492ad6f91700001000001f8c251ed6a594872bacfe286e28414e4`;
let pexelsUrl = `https://api.pexels.com/v1/search/?page=1&per_page=6&query=${word}`;
let headers = { Authorization: `Bearer ${pexelsApiKey}` };
axios.get(pexelsUrl, { headers: headers }).then(handlePexelsResponse);
}
function handleSubmit(event) {
event.preventDefault();
search();
}
function wordSearched(event) {
setWord(event.target.value);
}
if (loaded) {
return (
<div className="dictionary">
<section>
<form onSubmit={handleSubmit}>
<input
type="text"
autoComplete="off"
placeholder={props.suggestedSearch}
onChange={wordSearched}
/>
</form>
<div className="suggested-search">
suggested searches: forest, embroidery, stein, fascinator...
</div>
</section>
<Result result={result} />
<Photos photos={photos} />
</div>
);
} else {
load();
return "loading...";
}
}```
我建议您首先将所有api调用移到服务文件夹中。然后您也可以使用React Context。将您的道具(您必须将其从子项传递到父项(存储在该上下文中,每次您的道具更改触发API调用时。