【问题标题】:React Part of State is Empty Inside RenderReact 部分状态在渲染内部是空的
【发布时间】:2019-01-25 07:45:02
【问题描述】:

我有一个 react / Redux 应用程序。问题是我想在组件的状态下渲染一个元素列表,而这个列表在渲染方法执行时总是空的,我不能使用它。

这些元素来自 API 调用。

这是我的组件:

class PeopleView extends Component {

  static propTypes = {
    people: PropTypes.array,
    view: PropTypes.string
  }

  static stateToProps = state => ({
    people: state.properties.items || [],
    sortedPeople: sortBy(state.people.items || [], 'birthday'),
  })

  constructor(props) {
    super(props);
    const { people } = props;
    const sortedPeople = sortBy(people, 'birthday');

    this.state = {
      people: people,
      sortedPeople: sortedPeople,
      collapsed: true
    };
  }    

  toggleCollapsed = (e) => {
    this.setState({collapsed: !this.state.collapsed});
  }

  deleteHandler = (id) => {
    console.log("Person Id", id)    
  }

  render() {

    // THIS IS EMPTY: this.state.people = [] 
    // THIS IS NOT EMPTY: this.props.people = [{...}, {...}, {...}, ...]

    const sortedPeople = sortBy(this.props.people, 'createdAt');
    const sortedPeopleElements = this.props.sortedPeople.map((p, i) => {
      return <li key={p.id}>
        <Person index={i} id={p.id} name={p.name} onDelete={this.deleteHandler} />              
      </li>
    });    

    return (
      <div>
        <ul>
         {sortedPeopleElements}                  
        </ul>
      </div>
    );
  }
}

export default connect(PeopleView);

在 render 方法中 state 中的 people lis 始终为空,但 props 中的 people 列表始终没问题。这是为什么呢?

如何设置状态以使用渲染并开始从此列表中删除人员?

【问题讨论】:

  • connect() 中缺少参数
  • @xadm 我得到这个Uncaught ReferenceError: stateToProps is not defined 时将其更改为:connect(stateToProps)(PeopleView);
  • 因为你必须创建方法stateToProps
  • 为什么定义为静态?将其移出组件主体

标签: javascript reactjs ecmascript-6 redux react-redux


【解决方案1】:

在你的构造函数中:

constructor(props) {
    super(props);

/* Remove { } this brackets from the const variable and also you need props.people not props in it */
    const people  = props.people; 
    const sortedPeople = sortBy(people, 'birthday');

    this.state = {
      people: people,
      sortedPeople: sortedPeople,
      collapsed: true
    };
  }  

【讨论】:

    【解决方案2】:

    您的代码通常存在一些问题。

    1. this.state.people 仅在构造函数中从 this.props.people 的值初始化一次,如果您没有传入值,则默认为 undefined。请注意,您没有在 render 方法中的任何地方使用 this.state.people
    2. 您混淆了 React 的组件状态和 Redux 的状态。 Redux 的状态作为 props 传递给 React(通常通过一个名为 mapStateToProps 的映射函数,你可以随意调用它)。此映射函数需要传递给 connect(mapStateToProps)(PeopleView)。 react-redux 的 connect 函数是一个 curry 函数。
    3. 按照惯例,您确实不需要将stateToProps 设为组件类的静态方法。通常,它是该函数的顶级(或文件范围)。

    如果我能进一步澄清我的答案,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多