Javascript 将新元素插入空JSON对象
我试图将数据插入空的JSON数组,但遇到了问题。我在构造函数中定义数组,然后在页面加载时向后端发出几个get请求,在得到响应后,我希望将新的数组元素添加到现有的数组中。这是我正在使用的代码:Javascript 将新元素插入空JSON对象,javascript,Javascript,我试图将数据插入空的JSON数组,但遇到了问题。我在构造函数中定义数组,然后在页面加载时向后端发出几个get请求,在得到响应后,我希望将新的数组元素添加到现有的数组中。这是我正在使用的代码: constructor() { super(); this.state = { sds: [] } } componentDidMount() { axios.get('/userData', {
constructor() {
super();
this.state = {
sds: []
}
}
componentDidMount() {
axios.get('/userData', {
params: {
user: this.props.auth.user.name
}
}).then(res => {
for(var i=0; i<res.data[0].chemID.split(',').length; i++){
if(res.data[0].chemID.split(',')[i] != 0){
axios.get('/chemData', {
params: {
id: res.data[0].chemID.split(',')[i]
}
//This is where I want to insert the data
}).then(res => this.sds += ({
id: i,
title: res.data[0].chemName,
selected: false,
key: 'sds'
}))
}
}
})
}
constructor(){
超级();
此.state={
sds:[]
}
}
componentDidMount(){
get(“/userData”{
参数:{
用户:this.props.auth.user.name
}
})。然后(res=>{
对于(var i=0;i this.sds+=({
id:我,
标题:res.data[0]。化学名称,
选择:false,
键:“sds”
}))
}
}
})
}
+=
不是那样工作的。使用“排列”操作符复制数组的以前内容,然后手动将新对象添加到-
}).then((res) => {
const newThing = {
id: i,
title: res.data[0].chemName,
selected: false,
key: 'sds'
};
this.setState(prevState => ({
sds: [...prevState.sds, newThing]
}))
}
您不应该尝试自己改变状态,始终使用
setState
。在这种情况下,您可以传递一个函数作为第一个参数,它提供了以前的状态。这样,您可以确保保留this.state.sds中的任何内容,并将新对象添加到该数组中。您需要使用推送()方法将其添加到数组中,如下所示:
constructor() {
super();
this.state = {
sds: []
}
}
componentDidMount() {
axios.get('/userData', {
params: {
user: this.props.auth.user.name
}
}).then(res => {
for(var i=0; i<res.data[0].chemID.split(',').length; i++){
if(res.data[0].chemID.split(',')[i] != 0){
axios.get('/chemData', {
params: {
id: res.data[0].chemID.split(',')[i]
}
//This is where I want to insert the data
}).then(res => {
this.state.sds.push({
id: i,
title: res.data[0].chemName,
selected: false,
key: 'sds'
})
})
}
}
})
}
constructor(){
超级();
此.state={
sds:[]
}
}
componentDidMount(){
get(“/userData”{
参数:{
用户:this.props.auth.user.name
}
})。然后(res=>{
对于(var i=0;i{
这是国家队({
id:我,
标题:res.data[0]。化学名称,
选择:false,
键:“sds”
})
})
}
}
})
}
您可以尝试使用下一个示例:
this.state.sds[this.state.sds.length] = {
id: i,
title: res.data[0].chemName,
selected: false,
key: 'sds'
}
[已编辑]
正如@larz所说,您必须使用setState方法来避免代码的意外结果
var newSds = this.stage.sds;
newSds[newSds.length] = {
id: i,
title: res.data[0].chemName,
selected: false,
key: 'sds'
};
this.setState({ sds: newSds});
您可以在react和“状态更新已合并”中获得有关生命周期的更多信息
如果您没有使用react-setState方法than,则需要引用使用此.state.variableName的任何状态变量。要将哪些数据添加到何处?此.state={sds:[]}
是我定义它的地方。然后,在我发布的代码的底部,我正在执行一个this.sds+=
命令(这是错误的),但里面是我想要添加的参数!谢谢。这个.sds
不存在。为什么不应该存在@larzBecause它不是在任何地方定义的。它是在构造函数中定义的@LARSON,this.state.sds
是在构造函数中定义的。this.sds
不存在。切勿直接对状态进行变异。永远不要直接改变状态。同意。然后可以使用setState方法。(但要小心,它是异步的。)
You can use array.push().
this.state.sds.push(obj);