簡體   English   中英

React 組件道具不會更新

[英]React Component props won't update

當我發送圖像數組時, this.props.images沒有正確更新。 該數組僅顯示為空,但結果數組不是。

數組截圖

我已經為該項目鏈接了我的 repo 並列出了需要引用的文件。

React Web 應用程序倉庫

Furbabies Co 網絡應用程序

需要查看的文件如下:

  • 組件/內容/配置文件/Images.js
  • 組件/內容/User.js
  • 商店/image.js
  • 商店/images.js

如果你想通過貢獻來幫助這個項目,那就太好了! :)

也許你應該在組件生命周期中使用 componentWillReceiveProps

請參閱反應文檔--> 此處

或者只使用 pureComponents(函數下層類)

pureComponents 默認更新 props

我試過運行你的應用程序,但沒有用。 因此,下面的代碼假設其他所有內容都已在您的應用程序中設置並正常工作。

不要使用類裝飾器@ ,而是嘗試直接連接到類(另外,我強烈建議清理您的代碼,它真的很難閱讀)。

幾個注意事項:

  1. 為所有函數使用更好的聲明性名稱( this.update() -- update WHAT!?!? 雖然這對您來說很有意義,但對於從未見過您的應用程序的開發人員來說,他們會問同樣的問題)
  2. 按照推薦的方式設置redux reducer switch/case
  3. 將類似的 redux state 合並為一個 reducer。 例如,您有imageimages 有什么不同? 如果一個是用於索引的數字,另一個是用於圖像的數組,那沒關系,您仍然可以使用單個reducer(如下所示)。
  4. 創建一個actions文件夾來處理 Redux 動作和一個用於 Redux 類型的types文件夾
  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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM