You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引入React Alerts组件致应用报错,求助排查问题

问题解决:react-alert 引入组件后报错的问题

问题描述

我是React新手,跟着Traversy Media的YouTube教程学习。编写了Alerts组件使用withAlert高阶组件,在componentDidMount生命周期里调用alert.show方法,但将组件引入App.js后应用报错,注释掉<Alerts />后页面就能正常显示。

相关代码片段

Alerts.js

// Alerts.js
import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';

export class Alerts extends Component {
  componentDidMount() {
    this.props.alert.show("It Works");
  }
  render() {
    return <Fragment />;
  }
}

export default withAlert(Alerts);

App.js 完整代码

import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';

import { Provider as AlertProvider } from 'react-alert';
import AlertTemplate from 'react-alert-template-basic';

import Header from './layout/Header';
import Dashboard from './leads/Dashboard';
import Alerts from './layout/Alerts';

import { Provider } from 'react-redux';
import store from '../store';

// Alert Options
const alertOptions = {
    timeout: 3000,
    positon: "top center"
}


class App extends Component{
    render() {
        return (
            <Provider store={store}>
                <AlertProvider template={AlertTemplate} {...alertOptions}>
                    <Fragment>
                        <Header />
                        <Alerts />
                        <div className='container'>
                            <Dashboard />
                        </div>
                    </Fragment>
                </AlertProvider>
            </Provider>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('app'));

问题原因及解决方案

问题出在alertOptions对象的属性拼写错误:positon应该改为position。

react-alert的配置选项中不存在positon这个属性,错误的属性名会导致AlertProvider初始化异常,进而让被withAlert包裹的Alerts组件无法正确获取alert实例,最终引发报错。

修正后的alertOptions代码:

const alertOptions = {
    timeout: 3000,
    position: "top center"
}

修改后重新运行应用,Alerts组件就能正常调用this.props.alert.show显示提示了。

内容的提问来源于stack exchange,提问作者Sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:05:12