我在使用React钩子时遇到问题。
我有一个表单,其中我更新了一个添加元素的数组。我想在更新此数组时触发一个函数。这是我所做的:
import React from 'react';
import './App.css';
import Graph from './Components/Graph/Graph'
import AddNode from './Components/AddNode'
import AddLink from './Components/AddLink'
// import Data from './Assets/data.json'
let nodes = [
{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
]
let links = [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
function App() {
const addNode = node => {
console.log(nodes)
//nodes.push(node)
nodes = nodes.concat(node)
console.log(nodes)
}
const addLink = link => {
console.log(links)
//links.push(link)
links = links.concat(link)
console.log(links)
}
return (
<div className="App">
<Graph
nodes={nodes}
links={links}
/>
<AddNode
addNode={addNode}
/>
<AddLink
addLink={addLink}
/>
</div>
);
}
export default App;
控制台日志输出更新后的数组:
// before:
(4) [{…}, {…}, {…}, {…}]
0: {name: "Peter", label: "Person", id: 1, index: 0, x: 531.8419721919323, …}
1: {name: "Michael", label: "Person", id: 2, index: 1, x: 449.0976491010945, …}
2: {name: "Neo4j", label: "Database", id: 3, index: 2, x: 440.08459218524604, …}
3: {name: "Graph Database", label: "Database", id: 4, index: 3, x: 498.9750895616001, …}
length: 4
__proto__: Array(0)
// after:
(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "Peter", label: "Person", id: 1, index: 0, x: 531.8419721919323, …}
1: {name: "Michael", label: "Person", id: 2, index: 1, x: 449.0976491010945, …}
2: {name: "Neo4j", label: "Database", id: 3, index: 2, x: 440.08459218524604, …}
3: {name: "Graph Database", label: "Database", id: 4, index: 3, x: 498.9750895616001, …}
4: {name: "test", label: "a", id: 10}
问题是useEffect
组件中的Graph
无法运行:
function Graph(props) {
const {nodes, links} = props
...
const update = (svg, colors, simulation) => {
....
console.log('updating')
}
React.useEffect(() => {
update()
}, [nodes, links])
仅当我在浏览器中加载应用程序时,我才能看到控制台日志“正在更新”,此后,无论我添加了多少节点或链接,都不会再次触发该功能。
我想念什么?
答案 0 :(得分:1)
在您的App函数中使用useState
最初存储链接和节点的值
function App() {
const [linksState, setLinksState] = useState(links)
const [nodesState, setNodesState] = useState(nodes)
const addNode = node => {
newNodes = [...nodesState]
newNodes = newNodes.concat(node)
setNodesState(newNodes)
}
const addLink = link => {
newLinks = [...linksState]
newLinks = newLinks.concat(link)
setLinksState(newLinks)
}
return (
<div className="App">
<Graph
nodes={nodesState}
links={linksState}
/>
<AddNode
addNode={addNode}
/>
<AddLink
addLink={addLink}
/>
</div>
);
}