代码之家  ›  专栏  ›  技术社区  ›  AltBrian

类型错误:memberstore.members.map不是函数

  •  0
  • AltBrian  · 技术社区  · 6 年前

    我正在使用react和mobx构建一个小型web应用程序。最后的结果是与我安装的rails后端通信。现在我已经创建了一个memberstore,它有一个async fetchall()方法。

    import {observable, action, computed} from 'mobx';
    
    class MemberStore {
    @observable members = [];
    @observable isLoading = false;
    
    @action async fetchAll() {
        this.isLoading = false;
        const response = await fetch('http://localhost:3000/v1/members');
        const status = await response.status;
        if (status === 200) {
            this.members = response.json();
        } 
    
    }
    

    现在这个链接到了我的联系人页面,其中有一个react lifecycle方法 componentWillMount 是的。当它试图使用映射函数呈现项目时,我得到了上面的错误。下面是联系人页的代码。

    class Contact extends Component {
    componentWillMount(){
        this.props.MemberStore.fetchAll();
    }
    handleSubmit = (e) => {
        e.preventDefault();
    
        const name = this.member.value;
        const email = this.email.value;
        // const email = this.email.value;
        this.props.MemberStore.addMember({name, email});
        this.member.value = '';
        this.email.value = '';
    }
    render() {
        const {MemberStore} = this.props;
    
        return (
            <div>
                <Navbar />
                <Jumbotron title="Contact Page" subtitle="You want to get in   touch"/>
                <div className="container">
                   <h2>You have {MemberStore.memberCount} members.</h2>
    
                   <form onSubmit={e => this.handleSubmit(e)}>
                       <input type="text" placeholder="Enter Your Name" ref={input => this.member = input }/>
                       <div>
                       <input type="text" placeholder= "Enter Your Email" ref={input => this.email = input }/>
                       </div>
                       <button>Submit</button>
                   </form>
                   <ul>
                    {MemberStore.members.map(({name, email}, index) => (
                        <li key={index}>
                        <div>
                            name: {name}
                        </div>
                        <div>
                            email: {email}
                        </div>
                        </li>
                    ))}
                  </ul>
                </div>
                <Footer />
            </div>
          )
      }
     }
    

    任何帮助都将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  0
  •   idlefingers    6 年前

    response.json() 是一个承诺,所以你需要 await 那也是。假设您的api返回一个数组作为响应,它应该可以工作:

    @action async fetchAll() {
        this.isLoading = false;
        const response = await fetch('http://localhost:3000/v1/members');
        const status = await response.status;
        if (status === 200) {
            this.members = await response.json();
        }
    }