ReactJS,componentWillReceiveProps可以获取数据,但是渲染不能

时间:2019-05-09 19:18:00

标签: reactjs

我正在使用sagas进行ReactJS 15项目,并重新选择作为中间件来获取数据。我可以在 componentWillReceiveProps 中成功获取数据并将数据设置为状态,但是当我从状态获取数据时,第一次运行的render函数中仍然没有数据。有人知道这是怎么回事吗?顺便说一句,我使用json-server作为模拟数据服务器。下面是我的代码的一部分:

组件:

let randomNumber = function(first,second){
let number = Math.floor(Math.random()*Math.floor(second));
while(number<first){

    number = Math.floor(Math.random()*Math.floor(second));
}
return number;
}

action.js(正常工作):

 constructor(props) {
    super(props);
    this.state = {
      timelineData: [],
    };
  }

  componentDidMount() {
    // use react redux to make the api call here
    this.props.fetchTimelineData({
      id: parse(this.props.location.search.substr(1)).id,
    });
  }
 componentWillReceiveProps(nextProps) {
    console.log('nextProps', nextProps);
    // Successfully take the data from the nextProps (timelineData is not [])
    const { timelineData } = nextProps;
    this.setState({
      timelineData,
    });
  }

render() {
    // the first render called timelineData is an empty array, which will not able to populate the UI
    // which RaiseTimeline is empty
    const { timelineData } = this.state;
    return (
      <RaiseTimelineStyled>
        <RaiseDetailsGrid>
          <Accordion
            title={
              <RaiseAccordionHeader image={image} title={'Timeline'} />
          }>
            <Timeline.wrapper>
              <RaiseTimelineStyled.divider>
                <RaiseTimelineStyled.container>
                  <RaiseTimeline timelineEvents={timelineData} />

Api.js(正常运行):

export const setTimelineData = timelineData => console.log('actions.js', timelineData) || ({
  type: ACTIONS.SET_TIMELINE_DATA,
  timelineData,
});

减速器:(工作正常)

class TimelineAPI {
  // payload will be used after backend done
  static fetchTimelineData(payload) {
    return http.get(`${baseURI}/timeline`).then(result => console.log('api', result.data) || result.data);
  }
}

Sagas :(工作正常)

function TimelineDataReducer(state = initialState, action) {
  switch (action.type) {
    case ACTIONS.SET_TIMELINE_DATA:
      console.log('reducer', action.timelineData);
      return state.set('numbers', action.timelineData);
    default:
      return state;
  }
}

选择器(工作正常):

export function* fetchTimelineData(action) {
  yield put(togglePendingScreen(true));

  const { result, error } = yield call(TimelineAPI.fetchTimelineData, action.payload);

  if (error) {
    yield put(
      toggleErrorModal({
        isOpen: true,
        text: error.code,
        source: 'Fetch Timeline Data',
      }),
    );
  } else {
    console.log('Sagas', result.timeline);
    yield put(ACTIONS.setTimelineData(result.timeline));
  }
  yield put(togglePendingScreen(false));
}

2 个答案:

答案 0 :(得分:0)

在我看来,第一次运行没有数据是合乎逻辑的。

原因是在反应生命周期中,在componentDidMount()之前调用 render()函数一次。 (V15)

在此处查看15个生命周期的反应:https://gist.github.com/bvaughn/923dffb2cd9504ee440791fade8db5f9

答案 1 :(得分:0)

我得到了答案,一切都正确,但是另一个人的名字却另一个人的名字相同,并在构造函数中设置了它的状态,所以它不能在第一时间渲染