【发布时间】:2020-12-18 12:11:29
【问题描述】:
我是一名初学者 React 开发人员,我对这个特定的代码 sn-p 有疑问。
问题:
- 即使我直接复制了它的值并将其渲染为单独的子数据,也不是所有的虚拟数据都被渲染了
- 当我单击添加按钮创建新的输入表单时,它不会添加到渲染中。
我故意选择使用 useRef 而不是 useState,因为在用户添加或编辑他们想要的任何链接后,我想将 keyRef 发送到 NoSQL 数据库;而当我使用 useState() 时,它给了我陈旧的状态问题,其中包含所有链接的数组没有不断更新。
有什么建议吗?请,谢谢!
代码沙盒链接:https://codesandbox.io/s/react-hooks-counter-demo-forked-0bjdy?file=/src/index.js
App.js
import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
import { links } from './links';
import "./styles.css";
function App() {
const [loaded, setLoaded] = useState(false);
const formRef = useRef([]);
const keyRef = useRef([]);
if (!loaded) {
keyRef.current = links;
links.forEach(link => RenderLinks(link.id));
setLoaded(true);
}
function RenderLinks(id) {
const formLength = formRef.current.length;
if (id === null)
formRef.current = [ ...formRef.current, <AddLink key={formLength} id={formLength} /> ];
if (id && !formRef.current.find(form => form.props.id === id))
formRef.current = [ ...formRef.current, <AddLink key={formLength} id={formLength} /> ];
}
function AddLink(props) {
const id = props.id;
const value = keyRef.current[id] ? keyRef.current[id].link : '';
const [input, setInput] = useState(value);
keyRef.current = [
...keyRef.current,
{
id: id,
link: '',
}
];
return <input onChange={e => setInput(e.target.value)} value={input} />
}
return (
<div>
<button onClick={() => RenderLinks(null)}>add</button>
{formRef.current ? formRef.current.map(child => child) : null}
</div>
)
}
links.js 又名虚拟数据
export const links = [
{
id: 0,
link: "www.zero.com"
},
{
id: 1,
link: "www.one.com"
},
{
id: 2,
link: "www.two.com"
},
{
id: 3,
link: "www.three.com"
},
{
id: 4,
link: "www.four.com"
},
{
id: 5,
link: "www.five.com"
},
{
id: 6,
link: "www.six.com"
},
{
id: 7,
link: "www.seven.com"
}
];
【问题讨论】:
-
当你点击添加时,价值从何而来?我不确定,因为我看到 6 个输入
-
嘿!您正在添加另一个输入框。所以这将使它成为7个输入。输入框的值稍后会存储在keyRef和Firebase中,我没有在代码sn-p中添加。
标签: javascript reactjs react-hooks