我正在尝试在组件中进行初始获取,并在获取数据时呈现Loader。但是在isFetching变为true之前render()会调用,因此我的组件正在闪烁(isFetching = false => isFetching = true => isFetching = false)。
我知道我可以在没有数据的情况下仅渲染Loader,并且闪烁将消失,但是也许有人知道更优雅的解决方案?

actions / 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); });
  }
}


reducers / 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));

最佳答案

为什么不使初始状态的isFetching设置为true?使用createStore函数创建商店时,可以传递初始状态。

另外,React docs建议在componentDidMount中获取数据:

如果您需要从远程端点加载数据,这是实例化网络请求的好地方。在此方法中设置状态将触发重新渲染。

https://facebook.github.io/react/docs/react-component.html#componentdidmount

09-11 09:27