Vic*_*ina 0 javascript reactjs react-native react-hooks
我有一个数据数组,其中包含具有唯一 ID 的对象。
我正在尝试创建尽可能多的参考资料。例如,如果数组有 4 个元素,那么我将创建 4 个引用。每个引用都必须包含在一个数组中,而且我需要将其与对象的唯一 id 关联起来。
这是我试图在“伪代码”中执行的操作:
data = [{id: "10i3298yfrcd", ...}, {id: "y48hfeucldnjs", ...}]
references = data.map(({id}) => useRef(null))
Run Code Online (Sandbox Code Playgroud)
我不知道如何将每个创建的引用与其各自的对象 ID 关联起来(只是为了访问引用,例如使用字母数字索引数组,或类似的东西)...
另外,以这种方式创建引用时出现错误:
React 检测到 %s 调用的 Hook 顺序发生了变化。如果不修复,这将导致错误和错误。有关更多信息,请阅读 Hooks 规则:https://reactjs.org/docs/hooks-rules.html
所以我认为这不是动态创建引用的有效形式。
有什么想法如何做到这一点吗?谢谢。
这是根据 data.lenght 创建 useRef 的方法
import { useEffect, useRef, useState } from react;
const ArrayInputs = () => {
const inputRef = useRef([]);
const [data, setData] = useState([]);
useEffect( () => {
let data = ['Name', 'Age', 'Gender'];
inputRef.current = new Array(data.length);
setData(data);
}, []);
useEffect( () => {
//Example of using inputRef
if(data.length !== 0) {
inputRef.current[data.length - 1].focus();
}
}, [data]);
return(
<View>
{data.map( (element, i) => <TextInput ref = {el => inputRef.current[i] = el} />)}
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
833 次 |
| 最近记录: |