我有一個數字數組,當一個項目被添加到這個數組時,數字應該被這個項目替換。當另一個項目被添加到數組時,從數組中刪除項目
我遇到的問題是,大部分的時間將取代數量,但有時它會增加旁編號的項目。
我在拆卸項目時也有同樣的問題數量有時會出現項目旁邊。
而且它目前允許添加的項目進行了多次這樣,如果一個項目被添加兩次,它會顯示該項目的一個實例,刪除按鈕已被點擊了兩次實際刪除該項目。
我怎樣才能防止旁邊時添加/移除,並且還可以防止能夠添加一個項目一次以上的項目出現數量的行爲?
https://codesandbox.io/s/jp26jrkk89
Hello.js
import React from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'
import Product from './Product'
const NumberWrap = styled.div`
display: flex;
flex-wrap:wrap
border: 1px solid #ccc;
flex-direction: row;
`
const Numbers = styled.div`
display:flex;
background: #fafafa;
color: #808080;
font-size: 32px;
flex: 0 0 20%;
min-height: 200px;
justify-content: center;
align-items:center;
border-right: 1px solid #ccc;
`
const CardWrap = styled.div`
display:flex;
flex-wrap: wrap;
flex-direction: row;
margin-top: 20px;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
placeholder: [1, 2, 3, 4, 5],
addedArray: [],
data: [
{ id: 1, header: 'Item 1' },
{ id: 2, header: 'Item 2' },
{ id: 3, header: 'Item 3' },
{ id: 4, header: 'Item 4' }
],
addedItems: [],
}
}
handleAdd = (id) => {
const nextAdded = [id, ...this.state.addedArray];
this.setState({
addedArray: nextAdded,
addedItems: update(this.state.addedItems, {
$push: [
id,
],
})
})
}
handleRemove = (id) => {
const index = this.state.addedItems.indexOf(id);
const nextAdded = this.state.addedArray.filter(n => n != id);
this.setState({
addedArray: nextAdded,
addedItems: update(this.state.addedItems, {
$splice: [
[index, 1]
],
})
})
}
render() {
return (
<div>
<NumberWrap>
{
this.state.placeholder.map(num =>
<Numbers>
{this.state.addedArray.filter(n => n == num).length == 0 && num}
{
this.state.data.filter(item => {
return this.state.addedItems.indexOf(item.id) === num - 1;
}).slice(0, 5).map(item =>
<Product {...item} remove={() => { this.handleRemove(item.id) }} />
)
}
</Numbers>
)
}
</NumberWrap>
<CardWrap>
{
this.state.data.map(item =>
<Product
{...item}
add={() => {
this.handleAdd(item.id)
}}
/>
)}
</CardWrap>
</div>
)
}
}
Product.js
import React from "react";
import styled from "styled-components";
const Card = styled.div`
flex: 0 0 20%;
border: 1px solid #ccc;
`;
const Header = styled.div`
padding: 20px;
`;
const AddBtn = styled.button`
width:100%;
height: 45px;
`;
const Product = props => {
const { add, id, header, remove } = props;
return (
<Card>
<Header key={id}>
{header}
</Header>
<AddBtn onClick={add}>Add</AddBtn>
<AddBtn onClick={remove}>Remove</AddBtn>
</Card>
);
};
export default Product;
addedItems和addedArray的用法是什麼? –