递归渲染组件时,React-redux没有拾取状态

时间:2019-07-12 15:00:13

标签: javascript reactjs redux react-redux

我遇到一个问题,其中组件Question无法从我的react-redux存储正确接收数据。最初渲染组件时,它将毫无问题地从商店接收所需的数据。当问题变成子问题时,就会出现问题-在这种情况下,尽管是相同的代码,但不会检索存储中的数据,而是将其定义为未定义。子问题代码可以在下面看到,该代码在同一Question组件内呈现一个新的Question组件。此递归呈现的组件未收到正确的状态。

初始渲染代码段如下,位于Question的外部组件中:

<div style={{ paddingRight: '8px' }}>
  {data.Question.map(question => (
    <Question question={question} key={question.ID} />
  ))}
</div>

Question组件如下:

import React from 'react';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import FlexibleInput from '../Inputs/FlexibleInput';
import {checkConditionals} from '../../dataHelper';
import { connect } from 'react-redux';

const mapStateToProps = (state, ownProps) => {
  return {
    answers: state.answers,
    activeStep: state.stepper
  }
}

const mapDispatchToProps = { }

class Question extends React.Component {
  getStyle = () => {
    if (this.props.subQuestion) return {paddingLeft: '24px', paddingRight: '-12px'}
    return {}
  }

  render() {
    const question = this.props.question;

    console.log(this.props.activeStep, question.ID, this.props.answers);

    return (
      <React.Fragment>
        {checkConditionals(question, this.props.answers) ? (
          <div style={this.getStyle()}>
            {/*Grid is used to placed the question and the possible answers on the same line*/}
            <Grid container spacing={2}>
              <Grid item> {/*Grid item for the question's prompt*/}
                <Typography style={{padding: '12px', fontSize: '1rem'}}>
                  {question.Description}
                </Typography>
              </Grid>
              <Grid item> {/*Grid item for the question's answer options*/}
                <FlexibleInput obj={question}/>
              </Grid>
            </Grid>

            {/*Display a question's sub-questions if they exist, mapping each sub question in the array to a new section*/
              question.SubQuestion ? (  
              question.SubQuestion.map(subQuestion => (
                <Question question={subQuestion} key={subQuestion.ID} subQuestion={true}/>
              ))
            ) : (
              <React.Fragment></React.Fragment>
            ) }
          </div>
        ) : (
          <React.Fragment></React.Fragment>
        )}
      </React.Fragment>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Question);

1 个答案:

答案 0 :(得分:2)

Question本身无权访问商店。通过使用connect,您可以创建一个新组件,并且该组件可以访问商店。您确实在文件末尾使用了connect,并且导出了已连接的组件,因此就您的代码库的其余部分而言,一切都很好。但是在这个特定文件中,对<Question>的任何引用都是指 unconnected 组件。

也许这样做:


class Question extends React.Component {
  // ... later, in render
  question.SubQuestion.map(subQuestion => (
    <ConnectedQuestion question={subQuestion} key={subQuestion.ID} subQuestion={true}/>
  ))
}

const ConnectedQuestion = connect(
  mapStateToProps,
  mapDispatchToProps
)(Question);

export default ConnectedQuestion;