[英]Variable inside componentDidMount are undefined using Reactjs
我有以下代碼塊:
const UserNotification = ({ user }) => {
const url = `https://api.thingspeak.com/channels/${user.channel}/feeds.json?&dynamic=true`;
console.log(url); //https://api.thingspeak.com/channels/594944/feeds.json?&dynamic=true OK
return <UserNoti url = { url } />
}
class UserNoti extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
};
}
componentDidMount() {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
});
});
}
render() {...}}
但是,我得到的'url' is not defined no-undef
為以下行'url' is not defined no-undef
: componentDidMount()
fetch(url)
componentDidMount()
。 如何在componentDidMount方法內調用url變量?
使用this.props.url
訪問傳遞給UserNoti
類的url
屬性。
componentDidMount() {
fetch(this.props.url)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
});
});
}
在UserNotification
您將url
作為組件UserNotification
傳遞。 使用ES6類組件,可以使用this.props.propName
訪問道具。 因此,在您的情況下,您應該執行以下操作:
componentDidMount() {
fetch(this.props.url)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
});
});
}
有關組件和道具的官方React文檔的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.