componentDidMount中的函数未定义

bir*_*d03 5 javascript reactjs

我有以下代码块:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      avatar: '',
      ...some more data...
      }

      this.fetchUser = this.fetchUser.bind(this);
  }

  render() {
    return (
      <div>
        <SearchBox onSubmit={this.fetchUser}/>
        <Card data={this.state} />
        <BaseMap center={this.state.address}/>
      </div>
    );
  }

  componentDidMount() {
    function fetchUser(username) {
      let url = `https://api.github.com/users/${username}`;

      this.fetchApi(url);
    };

    function fetchApi(url) {
      fetch(url)
        .then((res) => res.json())
           .... some data that is being fetched .... 
        });
      };

    let url = `https://api.github.com/users/${this.state.username}`;
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

但是,我得到了TypeError: Cannot read property 'bind' of undefined以下一行:this.fetchUser = this.fetchUser.bind(this);constructor我将函数绑定到的位置this.

如何使函数(内部componentDidMount方法)可见且可用于绑定?

编辑:

我把这些功能放在里面componentDidMount的原因是因为StackOverflow上另一个用户的建议.他建议:

@BirdMars,因为你没有真正获取父级中的数据,并且状态并不真正保存地址对象.在父组件的componentDidMount中调用fetch并在那里更新状态.这将触发第二个渲染,它将使用地址对象传递新状态(第一个渲染将使用空状态.地址当然直到完成获取并更新状态)

Lyu*_*mir 11

这里有一些基本的误解,你仍然可以调用里面的函数componentDidMount,但你不应该在里面定义它们.

只需在外面定义功能componentDidMount,这将解决您的问题,这是一个简短的例子

componentDidMount() {
   this.fetchUser(this.state.username);
}

function fetchUser(username) {
   let url = `https://api.github.com/users/${username}`;
   this.fetchApi(url);
};

function fetchApi(url) {
   fetch(url)
   .then((res) => res.json())
      .... some data that is being fetched .... 
   });
};
Run Code Online (Sandbox Code Playgroud)