变量在反应组件中的函数外部不可用

时间:2017-11-07 22:14:43

标签: javascript reactjs

状态通过props传递(selectedCategory)。使用axios获取一个数组...它回来了,我可以在函数中控制它.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;

3 个答案:

答案 0 :(得分:3)

你要做的是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;

答案 1 :(得分:1)

问题是SearchCategoryMembers是一个异步函数,因此我们需要等待数据返回才能使用成员数据。

为此,我们可以从异步API请求中获取数据并更新父组件的状态。我们最初将members状态设置为空数组。当组件安装时,我们将请求数据,当它返回时,我们将更新members状态,然后将其传递给<Members />组件,然后将members数组传递给它

这是一个简化的工作示例:

function SearchCategoryMembers() {
  return axios.get('https://jsonplaceholder.typicode.com/posts');
}

class MembersWrapper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      members: []
    }
  }
  
  componentDidMount = () => {
    SearchCategoryMembers().then(data => {
      this.setState({
        members: data.data
      })
    });
  }

  render() {
    return (
      <Members members={this.state.members} />
    )
  }
}

function Members(props) {
  return (
    <ul>
      {props.members.map((member, id) => <li key={id}>{member.title}</li>)}
    </ul>
  )
}
ReactDOM.render(<MembersWrapper />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>

<div id="app"></div>

答案 2 :(得分:-2)

尝试Members.props.selectedCategory