【发布时间】:2020-09-28 02:31:43
【问题描述】:
我正在尝试合并从 2 个不同的 api 调用中获得的两个对象(此处的示例只是一个示例)。如何在用户状态下将对象的 UserId 数组和 userCredentials 数组合并在一起?我希望该州看起来像这个用户:[{id: 1, name"john", country="de"},{id: 2, name"micheal", country="us"}]
...
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
user: []
};
}
componentDidMount() {
//api call 1 receiving user Id and name
const UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
this.setState({ user: UserId });
//api call 2 receiving userCredentials
const userCredentials = [
{ id: 1, country: "de" },
{ id: 1, country: "us" }
];
this.setState({
user: { ...this.state.user, credentials: userCredentials }
});
}
render() {
console.log("values", this.state);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
</div>
);
}
}
...
我的示例代码是
https://codesandbox.io/s/fancy-water-5lzs1?file=/src/App.js:0-754
【问题讨论】:
-
您可以使用array.concat(anotherArray) 将两个数组合并在一起。
标签: javascript json reactjs rxjs