我正嘗試在數據獲取時在組件中執行初始提取並呈現Loader。但是在isFetching成爲true之前render()調用,因此我的組件閃爍(isFetching = false => isFetching = true => isFetching = false)。 我知道我可以在沒有數據的情況下呈現Loader,閃爍將消失,但也許有人知道更優雅的解決方案?顯示加載器,同時在react-redux組件中獲取初始數據
動作/ files.js
import 'whatwg-fetch';
import { REQUEST_FILES, RECEIVE_FILES } from '../constants'
export function requestFiles() {
return { type: REQUEST_FILES };
}
export function receiveFiles(files) {
const payload = files;
return { payload:payload, type: RECEIVE_FILES };
}
export function getFile(hash) {
return dispatch => {
dispatch(requestFiles());
fetch('/api/files/'+hash+'/info', {
method: 'GET',
})
.then(response => response.json())
.then(data => {
if (data.error) {
}
else {
dispatch(receiveFiles([data]));
}
})
.catch(error => { console.log('request failed', error); });
}
}
減速器/ files.js
import { REQUEST_FILES, RECEIVE_FILES } from '../constants'
var initialState = {
items: [],
isFetching: false
}
const files = (state = initialState, action) => {
switch (action.type) {
case RECEIVE_FILES: {
return { ...state, isFetching:false, items: action.payload };
}
case REQUEST_FILES: {
return { ...state, isFetching:true };
}
default:
return state;
}
}
export default files;
組件/智能/ fileboard.jsx
require('styles/app.scss');
import React from 'react';
import { Link } from 'react-router'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as filesActions from '../../actions/files'
import Loader from '../dumb/loader'
import withBoard from './board'
import DumbFileboard from '../dumb/fileboard'
let getFileSrc = require('config').default.getFileSrc;
const mapStateToProps = (state) => {
return {
files: state.files
}
}
const mapDispatchToProps = (dispatch) => {
return {
filesActions: bindActionCreators(filesActions, dispatch)
}
}
class Fileboard extends React.Component {
componentWillMount() {
if (this.props.files.items.length === 0) {
this.props.filesActions.getFile(this.props.params.hash);
}
}
constructor(props) {
super(props);
}
render() {
return this.props.files.isFetching ? Loader : (
<DumbFileboard fileSrc={ getFileSrc(this.props.files.items[0]) } />
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(withBoard(Fileboard));
我不能這樣做,因爲獲取時的情況下,不需要(例如,如果數據已被加載到前一頁)。 – ponyeatsrainbow
只要頁面共享相同的商店,您可以從整體狀態(即如果數據存在=>不需要獲取並且isFetching爲false)中獲得'isFetching'? –