繁体   English   中英

为什么状态值没有反映在 ReactJS 中?

[英]Why is the state value not reflecting in ReactJS?

class App extends Component {
  state = {
    name: ""
  };
  abc() {
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  }
  render() {
    return <div>ddd{this.state.name}</div>;
  }
}

this.state.name没有反映。 https://codesandbox.io/s/vigorous-sky-woxr7

我从外面调用这个函数。

我想从外部调用组件函数并更新状态。

这不是你编写 React 代码的方式。 你应该做这样的事情:

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      name: ""
    }
  }

  setName = _ => {
    this.setState({ name: 'John Doe' })
  }

  render() {
    return (
      <>
        <div>
          {`This is my name: ${this.state.name}`}
        </div>
        <button onClick={this.setName}>Click me to see my name!</button>
      </>
    );
  }
}

export default App;

需要考虑的两个重要关键:

  1. 状态必须在构造函数中启动
  2. 您必须有一个特定的函数来更新您可以从任何地方调用的状态。 如果您想在生命周期开始时启动它,请使用componentDidWount()方法。

更新:如果您想从该组件外部调用它

在这种情况下,您将有两个不同的组件,如果您想从子组件调用一个方法,您应该执行以下操作:

父组件

import React, { Component } from 'react';
import MyComponent from './MyComponent'

class App extends Component {
   onClick = () => {
    this.myComponent.method()
  }
  render() {
    return (
      <div>
        <MyComponent onRef={ref => (this.myComponent = ref)} />
        <button onClick={this.onClick}>MyComponent.method()</button>
      </div>
    );
  }
}

export default App;

子组件

import React, { Component } from 'react';

class MyComponent extends Component {
  componentDidMount() {
    this.props.onRef(this)
  }
  componentWillUnmount() {
    this.props.onRef(undefined)
  }
  method() {
    window.alert('Hello there, my name is John Doe!')
  }
  render() {
    return <h1>Example of how to call a method from another component</h1>
  }
}

export default MyComponent;

看看这里的一个活生生的例子: https : //repl.it/repls/AfraidNecessaryMedia

我建议你在类中调用你的类方法,但如果你想解决你的问题,请在 index.js 上使用React.createRef()

const rootElement = document.getElementById("root");
const ref = React.createRef();
ReactDOM.render(<App ref={ref} />, rootElement);
ref.current.abc();

https://codesandbox.io/embed/sleepy-glitter-fwplz

import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
window.a = function() {
  ref.current.abc();
};

class App extends Component {
  state = {
    name: ""
  };
  abc() {
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  }
  render() {
    return <div>ddd{this.state.name}</div>;
  }
}

const rootElement = document.getElementById("root");
const ref = React.createRef();
ReactDOM.render(<App ref={ref} />, rootElement);
window.a();

这个怎么样?

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    };
  }

  componentDidMount() {
    this.abc();
  }

  abc() {
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  }

  render() {
    return <div>ddd {this.state.name}</div>;
  }
}

您调用该函数的方式不正确。
请记住:需要调用一个函数...
对于您的第二个问题:您不能将函数从孩子调用到父母。
在这种情况下,您应该在父级中创建一个函数,发送给子级,然后在事件(组件加载、单击等)上调用它。
如果您真的需要这样做:将数据、函数等从子级发送到父级...检查 Reduxhttps : //redux.js.org/

这是您的代码工作(功能 abc 变化不大):

import React, { Component, Fragment } from "react"
import ReactDOM from "react-dom"    
import "./styles.css"

window.a = function() {
  var ab = new App()
  ab.abc()
}

class App extends Component {

state = {
    name: ""
  }

  abc = () => {
    this.setState({ name: "new name" })
  }

  render() {
    return (
      <Fragment>
        <div>{this.state.name}</div>
        <button onClick={this.abc}>call function</button>
      </Fragment>
    );
  }
}

const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)
window.a()

请注意使用';' 在每一行的末尾,不是编写 React js 的正确方法。
最佳实践链接: https : //americanexpress.io/clean-code-dirty-code/

你需要做两件事...

  1. 在构造函数中将abc()绑定到this或像我一样使用箭头函数,否则您将无法访问this.setState()
  2. 在生命周期方法中调用该函数,而不是在 React 之外使用ComponentDidMount()调用。

这是更新后的代码:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  state = {
    name: ""
  };
  abc = () => {
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  };
  componentDidMount() {
    this.abc();
  }
  render() {
    return <div>ddd {this.state.name}</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox 中的演示

因为abc()没有绑定到 this 并且方法使用 setState 这是这个对象中的一个方法,你有两种选择来解决这个问题:

1- this绑定到构造函数中的方法

2- 将您的功能实现为箭头功能而不是默认功能

对于第一种方法:

class App extends Component {
  constructor(props){
      super(props);
      this.state = {
          name: '',
      }

      this.abc = this.abc.bind(this);
  }
  abc(){
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  };
  componentDidMount() {
    this.abc();
  }
  render() {
    return <div>ddd {this.state.name}</div>;
  }
}


对于第二种方法:

class App extends Component {
  state = {
      name: '',
  }
  abc = () => {
    console.log("ddd");
    this.setState({
      name: "asd"
    });
  };
  componentDidMount() {
    this.abc();
  }
  render() {
    return <div>ddd {this.state.name}</div>;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM