我有下面的代碼塊:在我的功能結合到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