reactjs - 如果从反应钩子中的许多来源获取,如何防止重新渲染?
问题描述
我react hooks
在 React Native 中使用。我的问题是useState
初始化状态的函数会重新渲染。所以如果我设置如下状态
const [A, setA] = useState(false);
const [B, setB] = useState(false);
const [C, setA] = useState(false);
// ...
const testFunc = () => {
setA(true);
setB(true);
setC(true);
}
编辑 我认为例子是错误的。这是另一个例子。
const useFetch(coords) {
const [example, setExample] = useState([])
const [checker, setChecker] = useState(false);
const fetchData = () => {
axios.fetch(`url+${coords.latitue}+${coords.longitude}`).then(){
setExample(res.data());
setChecker(true);
}
}
useEffect(() => {
fetchData();
}, [coords])
return example;
}
const useLocation = () => {
...
return coords;
}
const App = () => {
const coords = useLocation();
const example = useFetch(coords); // example is undefined.
const [data, setData] = useState(example); // data is undefined.
}
它会导致与我使用 set 函数一样多的重新渲染。这是自然现象吗?如果我不想重新渲染,不能多次使用 set 函数吗?
解决方案
你不能以直接的方式做到这一点。我会为你推荐两种解决方案。
解决方案 1:在一个对象中组合状态。
const [value, setValue] = useState({A: false, B: false, C: false});
// ...
const testFunc = () => {
setValue({A: true, B: true, C: true});
}
解决方案 2:另一种解决方案是useReducer
.
const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
{A: false, B: false, C: false}
);
// ...
const testFunc = () => {
setState({A: true, B: true, C: true});
}
在这里,我实现了您的另一个示例:https ://stackblitz.com/edit/react-usestate-wcjshg
希望这对你有帮助!
推荐阅读
- r - 如何使用 for 循环在 R 中创建一个简单的表?
- c - 如果我想写另一个函数怎么办?
- java - 代码未正确翻译来自 Google Books API 的德语字符
- php - 如何将变量从java转换为php?
- python - Pytorch中神经网络的前向雅可比行列很慢
- spotfire - 按需提供详细信息的 Spotfire 脚本
- asp.net-core - 对 Azure SQL 数据库的 .NET Core 控制器 API 调用在 localhost 中有效,但在已部署的 Azure Web App 中无效
- java - 将文本文件转换为地图
> 使用 lambda - html - 位置固定将其下方的所有内容向下推以创建空白?
- c - 一个空数组如何参与计算?