我正在使用Mobx-React创建一个小型应用程序。我已经创建了一个成员存储,并具有一个asyn 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();
}
}
前端是带有以下代码的“联系人”页面。
import React, { Component } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import Jumbotron from '../components/Jumbotron';
import {inject, observer} from 'mobx-react';
@inject('MemberStore')
@observer
class Contact extends Component {
componentWillMount(){
this.props.members.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>
)
}
}
export default Contact;
我不确定是否应该是this.props.MemberStore.fetchAll()
,但是给了我一个不同的错误TypeError: MemberStore.members.map is not a function
。
因此,想知道我在访问MemberStore组件中的fetchAll()函数时我做错了什么。