[英]React Component props won't update
當我發送圖像數組時, this.props.images
沒有正確更新。 該數組僅顯示為空,但結果數組不是。
我已經為該項目鏈接了我的 repo 並列出了需要引用的文件。
需要查看的文件如下:
如果你想通過貢獻來幫助這個項目,那就太好了! :)
也許你應該在組件生命周期中使用 componentWillReceiveProps
請參閱反應文檔--> 此處
或者只使用 pureComponents(函數下層類)
pureComponents 默認更新 props
我試過運行你的應用程序,但沒有用。 因此,下面的代碼假設其他所有內容都已在您的應用程序中設置並正常工作。
不要使用類裝飾器@
,而是嘗試直接連接到類(另外,我強烈建議清理您的代碼,它真的很難閱讀)。
幾個注意事項:
this.update()
-- update WHAT!?!? 雖然這對您來說很有意義,但對於從未見過您的應用程序的開發人員來說,他們會問同樣的問題)image
和images
。 有什么不同? 如果一個是用於索引的數字,另一個是用於圖像的數組,那沒關系,您仍然可以使用單個reducer(如下所示)。actions
文件夾來處理 Redux 動作和一個用於 Redux 類型的types
文件夾fetch
)Upload Images
表單。 不要將它與您的Images
組件混為一談。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.