React Component道具不会更新

时间:2018-10-13 00:20:25

标签: javascript reactjs redux react-redux react-props

this.props.images在分发图像数组时未正确更新。数组只是显示为空,尽管结果数组不是。

screenshot of arrays

我已经链接了该项目的仓库,并列出了需要引用的文件。

React Web App Repo

Furbabies Co Web App

示例凭据:

  • 电子邮件:ana.gabriel2012@gmail.com
  • 密码:ana

您需要查看的文件如下:

  • components / Content / Profile / Images.js
  • components / Content / User.js
  • store / image.js
  • store / images.js

如果您想通过贡献力量来帮助该项目,那就太好了! :)

2 个答案:

答案 0 :(得分:1)

我尝试运行您的应用,但没有成功。因此,以下代码假定您的应用中所有其他内容均已设置并且可以正常运行。

不要使用类装饰器@,而应尝试直接连接到类(此外,我强烈建议清理您的代码,这确实很难阅读)。

一些注意事项:

  1. 为您的所有函数使用更好的声明性名称(this.update()-更新WHAT!?!?虽然对您有意义,但对于从未看过您应用的开发人员,他们会问同样的问题)
  2. 按照建议的方式设置redux reducer switch/case
  3. 将类似的redux状态合并为一个reducer。例如,您有imageimages。有什么不同?如果一个是用于索引的数字,另一个是用于图像的数组,那没关系,您仍然可以使用单个化简器(如下所示)。
  4. 创建一个actions文件夹来处理Redux操作,并创建一个types文件夹来处理Redux类型
  5. redux-thunk用于异步功能(例如fetch
  6. 创建一个单独的Upload Images表单。不要将其与Images组件混在一起。
  7. 您实际上实际上不需要Redux(除非您要与其他嵌套组件共享它)。您可以只使用React的本地state

types / index.js (redux操作类型)

export const UPDATE_IMAGE_INDEX = "UPDATE_IMAGE_INDEX";
export const UPDATE_IMAGES = "UPDATE_IMAGES";

reducers / imagesReducer.js (像这样构建switch/case的结构)

const initialState = {
   index: 0,
   data: []
}

const imagesReducer = (state=initialState, { type, payload }) => { //es6 destructing -- type=action.type, payload=action.payload
  switch (type) {
    case 'UPDATE_IMAGE_INDEX':
      return { ...state, index: payload } // accessible via state.images.index
    case 'UDPATE_IMAGES':
      return {...state, data: payload } // accessible via state.images.data
    default:
      return state
  }
};

export default imagesReducer;

动作/图像动作(redux动作创建者)

import * as types from '../types';

// the following is a Redux thunk action (thunk handles returned async functions -- you have to install it and add it as middleware)
export const fetchImages = (id, type) => dispatch => (
  fetch(`/images/${type}/${id}`) // fetch images
    .then(res => res.json()) // turn result into JSON
    .then(({ result }) => dispatch({ type: types.UPDATE_IMAGES, payload: result })) // send result to `imagesReducer`
    .catch(() => console.log('Network error...'));
)

// this updates the image index
export const updateImageIndex = payload => dispatch => (
  dispatch({ type: types.UPDATE_IMAGE_INDEX, payload })
)

// this should upload an image, save it, then return all current images
export const uploadImage = (type, id, data) => dispatch => (
   fetch(`/images/${type}/${id}`, {
      method: 'POST',
      body: data
     }
   )
   .then(res => res.json())
   .then(({ result }) => dispatch({ type: types.UPDATE_IMAGES, payload: result }))
   .catch(() => dispatch({ type: 'UPDATE_ERROR', payload: { message: 'Network error...try again later!'} }));
)

components / Content / Profile / ShowImages.js (显示图像-别无其他;也允许您通过按钮一个一个地查看它们)

import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { fetchImages, updateImageIndex } from '../../../actions/imageActions';

class ShowImages extends PureComponent {   
  componentDidMount = () => {
    inputs.lazyload(`/css/images.min.css`).catch(() => console.log('Network error...'));
    this.props.fetchImages(this.props.type, this.props.id); // fetches images via redux action creator shown above
  }

  handlePrevClick = e => {
    const { index, images } = this.props;
    if (index-1 <== images.length) {
       this.props.updateImageIndex(index-1); // reduces redux image index by 1 via redux action creator shown above
    }
  }

  handleNextClick = () => {
    const { index, images } = this.props;   
    if (index+1 <== images.length) {
       this.props.updateImageIndex(index+1); // increases redux image index by 1 via redux action creator shown above
    }
  }

  // ideally this should be done BEFORE being sent to the front-end, as is, every time this.props.index is updated, this has resort them -- ruins client-side performance and wastes resources.
  sortImages = () => {
   return this.props.images.sort((a, b) => {
      if (a.isDefault && b.isDefault) return a.src.localeCompare(b.src);
      return a.isDefault || b.isDefault;
    });
  }


  render = () => {
    const { index, images } = this.props;
    const sortedImages = this.sortImages();
    const prev = images.length && index > 0 ? '<' : '+';
    const next = images.length && index < images.length ? '>' : '+';

    return (
      <div className='images'>
        <button className='prev' onClick={this.handlePrevClick}>
          {prev}
        </button>
        <img src={sortedImages[index]} />
        <button className='next' onClick={this.handleNextClick}>
          {next}
        </button>
      </div>
    );
  }
}

const mapStateToProps = state => ({
   images: state.images.data,
   index: state.images.index,
   user: state.user,
   type: store.current.type
})

const mapDispatchToProps = dispatch => ({ fetchImages, updateImageIndex }); 


export default connect(mapStateToProps, mapDispatchToProps)(ShowImages)

答案 1 :(得分:0)

也许您应该在组件生命周期中使用componentWillReceiveProps

请参阅react docs --> here

或仅使用pureComponents(函数类)

pureComponents默认在道具上更新