我有下面的代码块:在我的功能结合到this
的constructor
this.fetchUser = this.fetchUser.bind(this);
:功能是不确定的
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;
不过,我得到了以下行TypeError: Cannot read property 'bind' of undefined
。
如何使componentDidMount
方法中的函数可见并可用于绑定?
编辑:
我把里面componentDidMount
功能的原因是因为在计算器上其他用户的建议。他建议:
@BirdMars是因为你不真的在父, 取数据和状态犯规真的保存地址对象。调用父项的 componentDidMount中的获取并更新那里的状态。这将 引发第二次渲染,将在新的状态通过与 地址对象(第一渲染会随着课程的一个空state.address ,直到完成读取和更新状态)
任何原因,你为什么不把'fetchUser'和'fetchApi'外'componentDidMount'? –
@BirdMars你可以在'componentDidMount'中调用这些函数,但在外部定义它们。 – Walk
为什么不移动'componentDidMount'之外的函数或根本不使用函数? – topher