我有一个动态创建的 React 组件,并将数据加载到其状态中。此状态在单击事件之间被清除,导致可见
信息丢失(未定义
)。它去哪儿了?
const React = require('react');
const ReactDOM = require('react-dom');
class App extends React.Component {
constructor(props) {
super(props);
this.nodesQuantity = 0;
this.state = {roots: []};
}
nextId(me) {
return me.nodesQuantity++;
}
componentDidMount() {
var roots = [1,2,3].map(node => {
let nextId = this.nextId(this);
return <Node key={nextId} data={node} nextId={this.nextId} depth={0} god={this} />
});
this.setState({roots: roots});
}
render() {
return (
<ul>{this.state.roots}</ul>
)
}
}
class Node extends React.Component{
constructor(props) {
super(props);
this.state = {data: this.props.data, childNodes: [], visible: true};
this.toggleExpanded = this.toggleExpanded.bind(this);
}
toggleExpanded(event) {
console.log(this.state.childNodes.length)
let val={id:"asdf",label:"asdf"}
if (this.state.childNodes.length > 0) {
this.state.childNodes.forEach((childNode) => {
childNode.setState({visible: !childNode.state.visible})
});
} else {
this.setState((oldState, props) => {
let nextId = props.nextId(props.god);
console.log(nextId);
oldState.childNodes.push(<Node key={nextId} data={val} nextId={props.nextId} depth={props.depth+1} god={props.god} />);
});
}
event.stopPropagation();
}
render() {
return (
<li onClick={this.toggleExpanded}>
{this.state.data.id} ({this.state.data.label})
<ul>{this.state.childNodes}</ul>
</li>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('react')
)
最佳答案
(oldState, props) => {
let nextId = props.nextId(props.god);
console.log(nextId);
oldState.childNodes.push(<Node key={nextId} data={val} nextId={props.nextId} depth={props.depth+1} god={props.god} />);
}
不返回任何内容...可能是您的未定义
的来源。您还可以通过推送来修改以前的状态,这在 react 文档中是禁止的:
prevState is a reference to the previous state. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from prevState and props.
你应该做类似的事情:
return {childNodes:[...(oldState.childNodes)]}
关于javascript - ReactJS 状态在事件之间丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964670/