我的Mobx商店中有以下获取请求:
getAllLegoParts = action("get all lego", () => {
this.legoParts = fromPromise(
fetch("http://localhost:8000/LegoPieces", {
method: "GET",
cache: "no-store"
}).then(response => response.json())
);
});
}
我在下面的ReactJS类中使用它:
class ViewLegos extends Component {
constructor(props) {
super(props);
this.props.store.getAllLegoParts();
}
render() {
console.log(this.props.store.legoParts.value);
return (
<div>
<table>
<thead>
<tr>
<th>Piece</th>
<th>Type</th>
</tr>
</thead>
<tbody>
{this.props.store.legoParts.map(legoPart => (
<tr key={legoPart.id}>
<td>{legoPart.piece}</td>
<td>{legoPart.piece}</td>
<td>{legoPart.type}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default inject("store")(observer(ViewLegos));
但是我有两个问题:
TypeError: this.props.store.legoParts.map is not a function
感谢你的帮助!
在获取显示数据之前是否可以等到组件已安装?这是一些可能有用的伪代码:
class ViewLegos extends Component {
componentDidMount() { fetchLegos() }
render() {
const allowRender = this.props.store.legoParts && this.props.store.legoParts.length
if (allowRender) {
// display lego data
}
return null
}
}
在此示例中,我们等待组件挂载,获取数据,并仅在存在时显示它。
仔细查看代码,当legoParts尚未定义时,您似乎需要更加防御并处理组件显示。由于在渲染之前您的异步提取无法完成,因此它们不会在开头定义。