我有以下代码块:
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() {...}}
但是,我在 componentDidMount()
中得到以下行的 'url' is not Defined no-undef
:fetch(url)
>。如何在 componentDidMount 方法中调用 url 变量?
最佳答案
使用 this.props.url
访问传递给 UserNoti
类的 url
属性。
componentDidMount() {
fetch(this.props.url)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
});
});
}
关于javascript - 使用 Reactjs 未定义 componentDidMount 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049951/