首页 > 解决方案 > 无法使用 Reactjs Toastr 读取未定义的属性成功

问题描述

我正在通过 此链接https://www.npmjs.com/package/react-toastr使用react toastr来获取我的 react-redux 表单。我已经安装了并且我已经按照要求进行了导入npm install --save react-toastr

import { ToastContainer } from "react-toastr";
import { ToastMessage } from "react-toastr";
import { ToastMessageAnimated } from "react-toastr";
let container;

src/index.html我有toastr.min.css 和 toastr.animate.css文件

在 RegisterPage 组件,当我按照下面的代码单击测试 Toastr 按钮时,一切正常

 <div className="container">
  <ToastContainer
    ref={ref => container = ref}
    className="toast-top-right"
  />
  <h1>
    React-Toastr
    <small>React.js toastr component</small>
  </h1>
  <div className="btn-container">
    <button
      className="primary"
      onClick={() =>
        container.success(`hi! Now is `, `success`, {
          closeButton: true,})
      }
    >
     Test Toastr
    </button>

  </div>

</div>

这是我想要做的。一旦表单注册成功,我想显示 toastr 消息警报,但它显示错误

bundle.js:36689 Uncaught TypeError: Cannot read property 'success' of undefined当我在user.service.js文件中添加以下代码时

setTimeout(()=>{ this.container.success(`hi! jmarkatti `, `success`, {closeButton: true,}); }, 400);

这是user.service.js文件

import config from 'config';
import { authHeader } from '../_helpers';

import { ToastContainer } from "react-toastr";
import { ToastMessage } from "react-toastr";
import { ToastMessageAnimated } from "react-toastr";
let container;

export const userService = {

    register,
    update,
};


function register(user) {
    const requestOptions = {
        method: 'POST',

return fetch(`../register.php`, requestOptions).then(handleResponse)
        .then(res => {

            if (res) {

//setTimeout(()=>{ this.container.success('Data added successfully'); }, 400);
setTimeout(()=>{ this.container.success(`hi! jmarkatti `, `success`, {closeButton: true,}); }, 400);
console.log('Data added suucessfully');
            }

            return user;
        });


}

下面的代码是 RegisterPage组件。

import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import { userActions } from '../_actions';

import { ToastContainer } from "react-toastr";
import { ToastMessage } from "react-toastr";
import { ToastMessageAnimated } from "react-toastr";
let container;

class RegisterPage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: {
                firstName: '',
                lastName: '',
                username: '',
                password: ''
            },
            submitted: false
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const { name, value } = event.target;
        const { user } = this.state;
        this.setState({
            user: {
                ...user,
                [name]: value
            }
        });
    }

    handleSubmit(event) {
        event.preventDefault();

        this.setState({ submitted: true });
        const { user } = this.state;
        const { dispatch } = this.props;
        if (user.firstName && user.lastName && user.username && user.password) {
            dispatch(userActions.register(user));
        }
    }

    render() {
        const { registering  } = this.props;
        const { user, submitted } = this.state;
        return (
            <div className="col-md-6 col-md-offset-3">

                <h2>Test Toastr</h2>

 <div className="container">
  <ToastContainer
    ref={ref => container = ref}
    className="toast-top-right"
  />
  <h1>
    React-Toastr
    <small>React.js toastr component</small>
  </h1>
  <div className="btn-container">
    <button
      className="primary"
      onClick={() =>
        container.success(`hi! Jmarkatti `, `success`, {
          closeButton: true,})
      }
    >
     Test Toastr
    </button>

  </div>

</div>

                <form name="form" onSubmit={this.handleSubmit}>

// form input removed to reduce code

                    <div className="form-group">
                        <button className="btn btn-primary">Register</button>
                        {registering && 
                                         }

                    </div>
                </form>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const { registering } = state.registration;
    return {
        registering
    };
}

const connectedRegisterPage = connect(mapStateToProps)(RegisterPage);
export { connectedRegisterPage as RegisterPage };

更新在这里

user.action.js代码

function register(user) {
    return dispatch => {
        dispatch(request(user));

        userService.register(user)
            .then(
                user => { 

/*
                   dispatch(success());
                    history.push('/login');
                    dispatch(alertActions.success('Registration successful'));
*/

                },
                error => {
                    dispatch(failure(error.toString()));
                    dispatch(alertActions.error(error.toString()));
                }
            );
    };

user.reducer.js代码

import { userConstants } from '../_constants';

export function registration(state = {}, action) {
  switch (action.type) {
    case userConstants.REGISTER_REQUEST:
      return { registering: true };
    case userConstants.REGISTER_SUCCESS:
      return {};
    case userConstants.REGISTER_FAILURE:
      return {};
    default:
      return state
  }
}

标签: reactjsredux

解决方案


试试这个

改变

   setTimeout(()=>{ this.container.success(`hi! jmarkatti `, `success`, {closeButton: true,}); }, 400);

    setTimeout(()=>{ 
            if(this.container){
                     this.container.success(`hi! jmarkatti `, `success`, {closeButton: true,}); 
             }
     }, 400);

推荐阅读