收到错误TypeError:无法使用React / Redux操作读取未定义的属性“ id”

泰勒·奥斯丁

我正在使用react / redux,并且使用操作调用deleteRequest之后发生错误。reducer从数组中删除了该项目,我认为这就是这种情况的原因,但是我应该更改位置,以便不再显示此页面。

直接错误来自this.props.deleteRecord于catch块下面的Post组件

我也在使用turbo,这就是我进行deleteRequest和存储数据的方式。如果您需要参考,请参阅文档。https://www.turbo360.co/docs

减速器:

import constants from '../constants';

const initialState = {
  all: null
};

export default (state = initialState, action) => {
  switch (action.type) {
    case constants.POST_CREATED:
      return {
        ...state,
        all: state.all.concat(action.data),
        [action.data.id]: action.data
      };

    case constants.RECORD_UPDATED:
      return {
        ...state,
        [action.data.id]: action.data,
        all: all.map(item => (item.id === action.data.id ? action.data : item))
      };

    case constants.RECORD_DELETED:
      const newState = {
        ...state,
        all: state.all.filter(item => item.id !== action.data.id)
      };
      delete newState[action.payload.id];

      return newState;

    case constants.FETCH_POSTS:
      const sortedData = action.data.sort((a, b) => {
        return new Date(b.timestamp) - new Date(a.timestamp);
      });
      return { ...state, all: sortedData };

    case constants.FETCH_POST:
      return { ...state, [action.data.id]: action.data };

    default:
      return state;
  }
};

零件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import swal from 'sweetalert2/dist/sweetalert2.all.min.js';

import actions from '../../actions';
import { DateUtils } from '../../utils';
import { Reply } from '../containers';
import { UpdateRecord } from '../view';

class Post extends Component {
  constructor() {
    super();
    this.state = {
      editShow: false
    };
  }

  componentDidMount() {
    const { id } = this.props.match.params;
    if (this.props.posts[id] != null) {
      return;
    }
    this.props
      .getRecord(id)
      .then(() => {})
      .catch(err => {
        console.log(err);
      });
  }

  updateRecord(params) {
    const { id } = this.props.match.params;
    const post = this.props.posts[id];
    const { currentUser } = this.props.user;
    if (post.profile.id !== currentUser.id) {
      swal({
        title: 'Oops...',
        text: 'Must be owner of post',
        type: 'error'
      });
      return;
    }

    this.props
      .updateRecord(post, params)
      .then(response => {
        swal({
          title: 'Success',
          text: `${currentUser.username} Your post has been updated!`,
          type: 'success'
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  deleteRecord() {
    const { id } = this.props.match.params;
    const post = this.props.posts[id];
    const { currentUser } = this.props.user;

    if (currentUser.id !== post.profile.id) {
      swal({
        title: 'Oops...',
        text: 'Must be owner of post',
        type: 'error'
      });
      return;
    }

    this.props
      .deleteRecord(post)
      .then(() => {
        this.props.history.push('/');

        swal({
          title: 'Post Delete',
          text: 'Please create a new post',
          type: 'success'
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    const { id } = this.props.match.params;
    const post = this.props.posts[id];
    const { currentUser } = this.props.user;
    if (post == null) {
      return <div />;
    }

    return (
      <div>
        <div className="jumbotron">
          <h1 className="display-3">{post.title}</h1>
          <div className="row" style={{ marginBottom: '25px' }}>
            <img className="img-fluid mx-auto" src={`${post.image}`} style={{ maxHeight: '400px' }} />
          </div>
          <p className="lead">{post.text}</p>
          <hr className="my-4" />
          {post.video == undefined ? null : (
            <div className="row justify-content-center">
              <div className="col-8">
                <div className="lead" style={{ marginBottom: '25px' }}>
                  <div className="embed-responsive embed-responsive-16by9">
                    <video style={{ background: 'black' }} width="800" controls loop tabIndex="0">
                      <source src={post.video} type={post.videoType} />
                      Your browser does not support HTML5 video.
                    </video>
                  </div>
                </div>
              </div>
            </div>
          )}
          <div className="lead">
            <Link to={`/profile/${post.profile.id}`}>
              <button className="btn btn-secondary btn-lg">{post.profile.username}</button>
            </Link>
            <p style={{ marginTop: '10px' }}>{DateUtils.relativeTime(post.timestamp)}</p>
          </div>
          {currentUser.id !== post.profile.id ? null : (
            <div className="row justify-content-end">
              <div className="col-md-2">
                <button
                  onClick={() => {
                    this.setState({ editShow: !this.state.editShow });
                  }}
                  className="btn btn-success"
                >
                  Edit
                </button>
              </div>
              <div className="col-md-2">
                <button onClick={this.deleteRecord.bind(this)} className="btn btn-danger">
                  Delete
                </button>
              </div>
            </div>
          )}
        </div>
        {this.state.editShow === false ? null : (
          <div>
            <UpdateRecord onCreate={this.updateRecord.bind(this)} currentRecord={post} />
          </div>
        )}
        <div>
          <Reply postId={post.id} />
        </div>
      </div>
    );
  }
}

const stateToProps = state => {
  return {
    posts: state.post,
    user: state.user
  };
};

const dispatchToProps = dispatch => {
  return {
    getRecord: id => dispatch(actions.getRecord(id)),
    updateRecord: (entity, params) => dispatch(actions.updateRecord(entity, params)),
    deleteRecord: entity => dispatch(actions.deleteRecord(entity))
  };
};

export default connect(stateToProps, dispatchToProps)(Post);
Medet Tleukabiluly

在这里看看

case constants.RECORD_DELETED:
  const newState = {
    ...state,
    all: state.all.filter(item => item.id !== action.data.id)
  };
  delete newState[action.payload.id];

  return newState;

action.data在过滤时以及action.payload从对象删除时使用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法读取未定义的属性“ id”

无法读取未定义的属性“id”

“TypeError:无法读取未定义的属性(读取'id')”

无法读取Redux thunk操作上未定义的属性'then'

类型错误:无法读取未定义错误的属性“_id”

错误类型错误:无法读取未定义的属性“_id”

删除模态。反应 Redux。无法读取未定义的属性“_id”

Gatsby TypeError-无法读取未定义的属性“ id”

JWT-TypeError:无法读取未定义的属性“id”

JavaScript TypeError:无法读取未定义的属性“ id”

Angular Material TypeError:无法读取未定义的属性“ id”

MERN-TypeError:无法读取未定义的属性“ id”

UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ id”

类型错误:无法读取未定义 ReactJs 的属性“_id”?

MongoDB错误“无法读取未定义的属性” _id”

类型错误:无法读取未定义 Flutter 的属性“id”

“错误”:POSTMAN 中的“无法读取未定义的属性 'id'”

react js无法读取未定义的属性“ id”

无法读取未定义的属性“ id”-REACT JS

TypeError:无法读取未定义的属性“ id”(用户未定义)

TypeError:无法读取未定义的属性(读取“id”) - React App

错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ id”

数组findIndex()函数-无法读取未定义的属性'id'

Serverless:“ errorMessage”:“无法读取未定义的属性” id“,

删除时出错:无法读取未定义的属性“ id”

无法读取未定义的select2的属性“ id”

无法读取未定义的属性“ id”。表示

角度4无法读取未定义的属性“ id”

Angular 2+无法读取未定义的属性“ id”