儘管使用了胖箭頭函數,但在使用setState時綁定了此上下文,我仍然不斷收到此錯誤。任何人都可以幫忙嗎?反應 - 無法讀取未定義的屬性'狀態'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
items: [],
repos: []
};
}
search(term) {
this.setState({
query: term
});
const clientId = '12489b7d9ed4251ebbca';
const secret = 'ff53ac9a93aaa9e7cddc0c009d6f068302866ff2';
function fetchUser() {
return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
}
function fetchRepos() {
return axios.get(`https://api.github.com/users/${this.state.query}?client_id=${clientId}client_secret=${secret}`);
}
axios.all([fetchUser(), fetchRepos()])
.then(axios.spread((items, repos) => {
this.setState({
items: items.data,
repos: repos.data
});
console.log(state);
}));
}
您是否能夠看到發生錯誤的代碼行? – webdeb
它在fetchUser上失敗。我只是添加這個變量。 const query = this.state.query; 謝謝修復它! –
添加到我的答案,你應該使用箭頭函數,因爲他們會重用父'這個' – webdeb