I have data that push to a state named value. and i want to display them based on number of array. i'm trying to make initiate but not work.
constructor(props) {
super(props)
this.state = {
json: [],
search: '',
value: [],
jumlah : "",
nama_barang : "Bolu kuwuk",
harga : 10000
}
}
i push jumlah, nama_barang and harga into value [] like this
handleSubmit(e){
e.preventDefault();
alert("Data Telah diinputkan!");
this.state.value.push(
this.state.jumlah,
this.state.nama_barang,
this.state.harga
)
this.setState(
this.state
)
console.log(this.state.value)
}
and display them like this
{this.state.value.map((v, i) => {
return <div key={i}>
<h1>{v.jumlah}</h1>
<h1>{v.nama_barang}</h1>
<h1>{v.harga}</h1>
</div>
})}
it works when i write {v} but it print whole array. i just want display it by number of array
When you push
into your array, you are adding 3 new elements to that array as opposed to one object that contains jumlah
, nama_barang
, and harga
.
What you should be doing is:
this.state.value.push({
jumlah: this.state.jumlah,
nama_barang: this.state.nama_barang,
harga: this.state.harga,
});
This will make it work as expected, but you are mutating state and setting setState
to this.state
-- these 2 things are against best practice.
Try this instead:
this.setState((prevState) => {
return {
value: prevState.value.concat([{
jumlah: this.state.jumlah,
nama_barang: this.state.nama_barang,
harga: this.state.harga,
}])
}
});
In the code above we are not mutating the existing state object, and we are using an updater callback in setState
that contains a reference to our previous state (the rule is that we should use the updater syntax whenever our new state depends on our previous state)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.