javascript - ReactJS 状态在事件之间丢失

标签 javascript reactjs

我有一个动态创建的 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/

相关文章:

javascript - AngularJS 将数据从服务返回到 View

Javascript 确认多项更改

javascript - ionic 列表中的图标不可点击

javascript - 在循环中通过setState添加className

reactjs - 将 expandIcon 图标向右移动并从扩展表中移除空白区域 Ant Design reatc js

javascript - 根据数字输入部署多个div

forms - React 中的嵌套表单状态和一个 onChange 函数

javascript - ReactJS:是否可以在子组件中包含父组件?

javascript - 有没有办法在react-navigation(react-native)中保存和恢复导航历史记录

javascript - 删除 arrayItem[index] 使元素占位符保持未定义状态