Console.log 打印两次并且地图在 reactjs/mobx 项目中不起作用
Console.log prints twice and map doesn't work in reactjs/mobx project
我的 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:
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));
但是我有两个问题:
Console.log 打印两次 - 在一种情况下打印未定义,在第二次打印对象数组(这是我想要的)。
我收到一条错误消息:
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 时加强防御并处理组件显示。由于您的异步提取不会在渲染之前完成,因此它们不会在一开始就被定义。
我的 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:
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));
但是我有两个问题:
Console.log 打印两次 - 在一种情况下打印未定义,在第二次打印对象数组(这是我想要的)。
我收到一条错误消息:
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 时加强防御并处理组件显示。由于您的异步提取不会在渲染之前完成,因此它们不会在一开始就被定义。