通过道具(selectedCategory)传递状态。使用axios获取数组...它回来了,我可以在函数中进行console.log记录。我想将其分配给变量,然后在函数外部进行映射。但是它不可用(未定义)

import React from 'react';
import SearchCategoryMembers from '../libs/category-members';

import MemberItem from './member_item';

const Members = ({ selectedCategory }) => {
  if (!selectedCategory) {
    return <div className="none" />;
  }

  SearchCategoryMembers({ categoryTitle: selectedCategory.title }, members => {
    console.log(members);
  });

  // members not available to map over outside of function

  return <ul className="member-list" />;
};

export default Members;

最佳答案

您正在尝试做的是React中的常见范例。您正在从某个外部来源请求数据,然后一旦检索到我的猜测,您想将其呈现在此组件中,但是您正在尝试使用无状态组件来进行处理。您需要一种跟踪SearchCategoryMembers中的回调何时完成的方法。您必须使用状态。

import React, { Component } from 'react';
import SearchCategoryMembers from '../libs/category-members';

import MemberItem from './member_item';

class Members extends Component {

  constructor(props) {
    super(props);

    // We'll put our members here once we get them back
    this.state = { };
  }

  // This is generally where you want to make api calls in the react lifecycle
  componentDidMount() {
    const selectedCategory = this.props.selectedCategory;
    if (!selectedCategory) return;
    SearchCategoryMembers(
      { categoryTitle: selectedCategory.title },
      members => {
        // now we have our members data, set it on state
        this.setState({ members: members });
        // or fancy es6 shorthand: this.setState({ members });
      }
    );
  }

  render() {
    // my guess is you want to render something about the members here
    if (!this.state.members) return null;
    return (
      <ul>
        {this.state.members.map((member) => <li>{member.name}</li>)}
      </ul>
    );
  }

}

export default Members;

关于javascript - 变量在React组件中的函数外部不可用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47168310/

10-16 10:45