reactjs - ReferenceError:未定义组件
问题描述
import React from 'react';
import axios from 'axios';
class App extends React.Component {
state = { advice: '' };
componentDidMount() {
this.fetchAdvice();
}
fetchAdvice = () => {
axios.get('https://api.adviceslip.com/advice')
.then((response) => {
const { advice } = response.data.slip;
this.setState({advice});
})
.catch((error) => {
console.log(error);
})
}
render () {
const { advice } = this.state;
return (
<div className="app">
<div className="card">
<h1 className="heading">{advice}</h1>
<button className="button" onClick={this.fetchAdvice}>
<span>Give Me Advice!</span>
</button>
</div>
</div>
);
}
}
export default App;
解决方案
根据您的评论,您正在调用 App
<li> <Link href="#advice"> <NavLink onClick={App}>Get an Advice</NavLink> </Link> </li>
您调用 App 的方式是错误的。这会将 App 作为函数绑定到事件 onClick。这不是使用 React 类组件或 React 路由器链接的方式。
提供一个to
参数值,并使用 Switch 语句将其映射到 Route 中的 App。
作为参考,请查看此示例 https://reactrouter.com/web/example/basic
推荐阅读
- python - 多层次查询深度嵌套复杂的 JSON 数据
- json - 如何从 Json 文件 discord.py 中读取数据
- reactjs - 在 React.js 中将用户数据从 useEffect() 保存到 useContext() 之前加载页面
- python - 如何将结构中的给定残基突变为 biopythhon 中的不同氨基酸?
- kernel - 是否有 64 位 UEFI ELF 引导加载程序?
- winapi - MFC:如何保存和恢复 CEditView 滚动位置以便正确滚动内容?
- python - 更改顺序 x 轴 matplotlib
- java - War适用于tomcat,但不适用于wildfly
- ros - 错误:试图通告已在此节点中通告的服务
- python - Pandas astype('int') 中的奇怪问题(错误?)