gpt4 book ai didi

javascript - 为什么 componentDidUpdate 看不到新插入的 dom 节点?

转载 作者:行者123 更新时间:2023-12-03 05:32:18 26 4
gpt4 key购买 nike

我有这个奇怪的情况,也许我在 react componentDidMount 的工作方式中遗漏了一些东西,或者也许这是一个奇怪的行为(正确知道我无法提供真正的 jQuery 插件的 fiddle ) ,但我很确定问题比插件本身更广泛)。

var Hello = React.createClass({
getInitialState() {
return {content: '<div id="target">ciao!</div>'}
},

componentDidMount() {
const target = $('#target').init();
this.target = target;
},

componentWillReceiveProps(nextProps) {
if (condition) {
this.target.destroy(); // this remove even the DOM node
}
},

componentDidUpdate() {
const target = $('#target').init(); // HERE PROBLEM! can't find the #target element
this.target = target;
}

render: function() {
return <div>Hello {this.state.content}</div>;
}
});

我不明白为什么在“条件”成立并且 dom 节点被插件破坏后,componentDidUpdate 找不到该 #target在我看来,应该在 componentWillReceiveProps 之后的第一次渲染中“重新渲染”。我希望能够在那里,因为它从永不改变的初始状态读取它。

我错过了什么?

最佳答案

由于您使用 jQuery 操作 React 元素 (this.state.content),这使得 React 无法检测到渲染内容的更改。所以当你第一次渲染它时

  1. componentDidUpdate 具有初始状态和完全渲染的组件,包括 #target
  2. 调用$('#target').init()后,渲染的组件在外部发生更改,而不通知React
  3. 调用 $('#target').destroy() 后,#target 节点会从 DOM 中移除,且不会通知 React
  4. 因此,当在 componentDidUpdate 中调用 $('#target').init() 时,您无法找到 #target因为 React 没有检测到 #target 中的任何变化,并且由于 React 会选择性地重新渲染,所以 #target 不会重新生成。

因此,您可以做的一件事就是更新 componentWillReceiveProps ( in condition check ) 中的状态,请注意 data-updated 字段,这将确保 React 检测到 this.state.content,因此会重新渲染组件,你会在componentDidUpdate

中再次找到 #target
componentWillReceiveProps(nextProps) {
if (condition) {
this.target.destroy(); // this remove even the DOM node
this.state.content = `<div id="target" data-updated="${Date.now()}">ciao!</div>`;
}
}

鉴于此,我建议您查看refs在 react 中。

关于javascript - 为什么 componentDidUpdate 看不到新插入的 dom 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40890362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com