首页 > 解决方案 > 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;

标签: reactjs

解决方案


根据您的评论,您正在调用 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


推荐阅读