首页 > 解决方案 > 获取新数组状态时反应类型错误

问题描述

我正在尝试转换此代码

// this.setState({
//     description:'',   // resets title after upload
//     images: [
//       {
//         id: newImage[0].id,
//         user:{
//             username: newImage[0].user.username
//         },
//         // comments:{
//         //   comment_body: newImage[0].comments.comment_body  
//         // },
//         image_title: newImage[0].image_title,
//         img_url: newImage[0].img_url,
//         created_at: new Date().toLocaleString().replace(',', ''),
//         updated_at: new Date().toLocaleString().replace(',', '')
//       },
//       ...this.state.images
//     ]
//   })

对于redux reducer,这是我的尝试

片段缩减器

case UPLOAD_IMAGE:
const newState = {...state}
const myImages = newState.images // old images

const newImage = action.newImage
console.log(newImage); // gets the new uploaded image. 
return {
    images:[
        ...myImages,
        {
            id: newImage[0].id,
            user:{
                username: newImage[0].user.username
            },
            // comments:{
            //   comment_body: newImage[0].comments.comment_body  
            // },
            image_title: newImage[0].image_title,
            img_url: newImage[0].img_url,
            created_at: new Date().toLocaleString().replace(',', ''),
            updated_at: new Date().toLocaleString().replace(',', '')
        }

    ]

}

截至目前,images[] 被映射到仪表板组件中,它从 redux reducer 获取图像 case GET_IMAGES:。上传图片时出现问题。我得到错误

TypeError:无法读取未定义的属性“长度”

刷新时,新上传的图像会显示在地图迭代中。

我的猜测是旧图像包含在一个数组中,而新图像位于我想我不知道的对象内的数组中。

旧图像数据结构(为保护隐私而编辑)

[
  {
    "id": 217,
    "image_title": "ddddddf",
    "img_url": "http:/************579/uploads/lshndpj***g",
    "created_at": "2019-06-16T17:03:00.605Z",
    "updated_at": "2019-06-16T17:03:00.605Z",
    "user_id": 1,
    "user": {
      "id": 1,
      "googleId": null,
      "username": "E****",
      "password": *****$12$16UTTfIH6gXhnRMnBHFGHuHiI***EAGF3GCjO62",
      "email": "e****",
      "created_at": "2019-06-05T04:50:20.133Z",
      "updated_at": "2019-06-05T04:50:20.133Z"
    },
    "comments": []
  },

新上传的图像数据结构(为隐私而编辑)

{
  "0": {
    "id": 218,
    "image_title": "owl",
    "img_url": "http:/*********0705077/uploads******",
    "created_at": "2019-06-16T17:11:19.066Z",
    "updated_at": "2019-06-16T17:11:19.066Z",
    "user_id": 1,
    "user": {
      "id": 1,
      "googleId": null,
      "username": "BOB",
      "password": "$2b$12******"
      "created_at": "2019-06-05T04:50:20.133Z",
      "updated_at": "2019-06-05T04:50:20.133Z"
    },
    "comments": []
  },

也许数据结构存在差异,这就是为什么它在遍历数组时给我类型错误的原因。

完整代码

行动

export const uploadImage = data =>  {
   return (dispatch) => {
    Axios.post('/images/upload', data).then((response) => {
        const newImage = {...response.data}
        console.log(newImage);
        dispatch({type:UPLOAD_IMAGE, newImage})    
   } 

}


// get images
export const getImages = () => {
    return (dispatch) => {
        return Axios.get('/images/uploads').then( (response) => {
                const data = response.data;
                dispatch({ 
                    type: GET_IMAGES,
                    data
                })
            });
    }
}

减速器

import { GET_IMAGES, POST_COMMENT, DELETE_IMAGE, UPLOAD_IMAGE } from '../actions/types';

const initialState = {
    images:[],

}

export default  (state = initialState, action) => {
    switch (action.type) {
        case GET_IMAGES:
            console.log(action.data);
            return{
                ...state,
                images:action.data
            }
        case UPLOAD_IMAGE:
            const newState = {...state}
            const myImages = newState.images // old images

            const newImage = action.newImage
            console.log(newImage); // gets the new uploaded image. 
            return {
                images:[
                    ...myImages,
                    {
                        id: newImage[0].id,
                        user:{
                            username: newImage[0].user.username
                        },
                        // comments:{
                        //   comment_body: newImage[0].comments.comment_body  
                        // },
                        image_title: newImage[0].image_title,
                        img_url: newImage[0].img_url,
                        created_at: new Date().toLocaleString().replace(',', ''),
                        updated_at: new Date().toLocaleString().replace(',', '')
                    }

                ]

            }
        default:
            return state;
    }
}

仪表板.js

const { image} = this.props

{image.images.length > 0 ? (
        image.images.map( (img, i) => (   
            <div key={i}>
                <ImageContainer img={img} deleteImg={() => this.deleteImg(img.id)}/>
            </div>      
        ))
    ) : (
    <div>
        <Grid item md={8}>
            <Typography>No Images yet</Typography>
        </Grid>
    </div>
)}
const mapStateToProps = (state) => ({
   image: state.image
})
const mapDispatchToProps = (dispatch) => ({
   getImages: () => dispatch(getImages()),
   deleteImage : (id) => dispatch(deleteImage (id)),
   uploadImage: (data) => dispatch(uploadImage(data))
})
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)

标签: reactjsredux

解决方案


在@mezba 和@Abhay Sehgal 的帮助下

我找到了一个可行的解决方案,谢谢大家

 case UPLOAD_IMAGE:
            const newState = {...state}
            const myImages = newState.images // old images

            const newImage = action.newImage
            console.log(newImage[0]); // gets the new uploaded image. 
            return {
                images:[

                    {
                        id: newImage[0].id,
                        user:{
                            username: newImage[0].user.username
                        },
                        // comments:{
                        //   comment_body: newImage[0].comments.comment_body  
                        // },
                        image_title: newImage[0].image_title,
                        img_url: newImage[0].img_url,
                        created_at: new Date().toLocaleString().replace(',', ''),
                        updated_at: new Date().toLocaleString().replace(',', '')
                    },
                    myImages[0]

                ]

            }

推荐阅读