我有一个从API获取的组件。它还接收set + setState,这使得每次状态更新时都会重新渲染它,从而一遍又一遍地从api获取。
有什么主意我可以阻止它重新获取吗?
import React, { useState } from "react";
import Select from "./Select";
const App = () => {
const [state, setState] = useState([]);
return (
<div>
<Select state={state} name="email" setState={setState} />
<span>
current state <b>{state.email}</b>
</span>
</div>
);
};
export default App;
import React, { useState, useEffect, useRef } from "react";
// import { instance } from "../../stores/UserStore";
import axios from "axios";
const Select = ({ state, setState, name, ...props }) => {
const [data, setData] = useState([]);
const renders = useRef(0);
useEffect(() => {
let isCurrent = true;
if (isCurrent) {
axios
.get("https://jsonplaceholder.typicode.com/posts/1/comments")
.then(res => setData(res.data));
}
return () => (isCurrent = false);
}, []);
useEffect(() => console.log(state), [state]);
return (
<div>
<p>renders: {renders.current++}</p>
<select
name={name}
value={state[name]}
{...props}
size="5"
onChange={event => {
setState({ ...state, [event.target.name]: event.target.value });
}}
>
{data.map(item => (
<option key={item.email} value={item.email}>
{item.email}
</option>
))}
</select>
</div>
);
};
export default Select;
此外,这里的codeandbox:https://codesandbox.io/s/input-rerender-issue-eyb3o