Используя ту же функцию в 2 реагирующих компонентах. Второе не работает - PullRequest
0 голосов
/ 31 марта 2020

Я борюсь с TypeError: deleteEducation не является функцией - та же функция в 2 компонентах React.

Этот компонент работает.

    import React, { Fragment } from 'react'
    import PropTypes from 'prop-types';
    import { connect } from 'react-redux';
    import Moment from 'react-moment';
    import { deleteEducation } from '../../actions/profile';


    export const Education = ({ education, deleteEducation }) => {
        const educations = education.map(edc => (
            <tr key={edc._id}>
                <td>
                    <button className='btn btn-danger' onClick={() => deleteEducation(edc._id)} >Delete</button>
                </td>
            </tr>
        ));
        return (
            <Fragment>
                <h2 className='my-2'>Education Credentials</h2>
                <table className="table">
                    <tbody>
                        {educations}
                    </tbody>
                </table>
            </Fragment>
        )
    }

    Education.propTypes = {
        education: PropTypes.array.isRequired,
        deleteEducation: PropTypes.func.isRequired,
    }

    export default connect(null, { deleteEducation })(Education);

Это не так. Я хотел бы использовать другой метод для удаленияExperience (). Это не сработало, поэтому я попробовал ту же функцию, но имя компонента отличается.

import React, { Fragment } from 'react'
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Moment from 'react-moment';
import { deleteEducation } from '../../actions/profile';


export const Experience = ({ education, deleteEducation }) => {
    const educations = education.map(edc => (
        <tr key={edc._id}>
            <td>
                <button className='btn btn-danger' onClick={() => deleteEducation(edc._id)} >Delete</button>
            </td>
            </tr>
    ));
    return (
            <Fragment>
                <h2 className='my-2'>Education Credentials</h2>
                <table className="table">
                    <tbody>
                        {educations}
                    </tbody>
                </table>
            </Fragment>
    )
}

Experience.propTypes = {
    education: PropTypes.array.isRequired,
    deleteEducation: PropTypes.func.isRequired,
}

export default connect(null, { deleteEducation })(Experience);

Не могу понять, что не так

        <Fragment>
            <DashboardActions />
            {profile.education.length ===  0 ? null : (<Experience education={profile.education} />)}
            {profile.education.length === 0 ? null : (<Education education={profile.education} />)}
        </Fragment>

Это моя ошибка

TypeError: deleteEducation is not a function
onClick
F:/DevConnector/client/src/components/dashboard/Experience.js:22
  19 |             )}
  20 |         </td>
  21 |         <td>
> 22 |             <button className='btn btn-danger' onClick={() => deleteEducation(edc._id)} >Delete</button>
     | ^  23 |         </td>
  24 |         </tr>
  25 | ));

Моя отправленная функция

export const deleteEducation = id => async dispatch => {
    try {
        const res = await axios.delete(`/api/profile/education/${id}`);
        dispatch({
            type: UPDATE_PROFILE,
            payload: res.data,
        })
        dispatch(setAlert('Education Removed', 'success'));

    } catch(err) {
        console.log(err);
        const errors = err.response.data.errors;
        if(errors) {
            errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
        } 

        dispatch({
            type: PROFILE_ERROR,
        })
    }
}

Ответы [ 2 ]

0 голосов
/ 31 марта 2020

Мой импорт был неправильным, который не был включен в мой пост. Извините, React автоматически добавил импорт по умолчанию, а я не заметил.

import { Experience }  from './Experience';
import Education from './Education';
0 голосов
/ 31 марта 2020

Вам необходимо передать свою функцию с параметрами в оболочке подключения в обоих компонентах.

Изменить

export default connect(null, { deleteEducation })(Experience);

на

const mapDispatchToProps = dispatch => ({
  deleteEducation: id => dispatch(deleteEducation(id))
})
export default connect(null, mapDispatchToProps)(Experience);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...