如何在 React 中按另一个数组过滤数组?
How to Filter an Array by Another in React?
我推入 arr1
的所有内容都应该从 arr2
的映射中删除,而是返回新推入的值。这是为什么?
const [arr1, setArr1] = React.useState([]);
const arr2= ['banana', 'coconut', 'milk']
React.useEffect(() => {
initList()
}, [])
function add (t) {
setArr1(...arr1, t.currentTarget.value)
console.log('arr1: ' + arr1)
}
function initList () {
setArr1(arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 =>
<li>
<input
onChange={add}
type='radio'
name='arr1'
value={arr2}
id={arr2}
/>
<label
for={arr2}
>
{arr2}
</label>
</li>
));
}
return (
<div>
{arr1}
</div>
)
- 不要将 JSX 元素保持在状态 (arr1)。状态变量只包含数据。
- setArr1(...arr1, t.currentTarget.value) --> 这里没有设置为数组。更新为 setArr1([...arr1, t.currentTarget.value])
试试这个片段。
const Test = () => {
const [arr1, setArr1] = React.useState([]);
const arr2= ['banana', 'coconut', 'milk']
function add (t) {
setArr1([...arr1, t.currentTarget.value])
console.log('arr1: ' + arr1)
}
return (
<div>
{arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 =>
<li>
<input
onChange={add}
type='radio'
name='arr1'
value={arr2}
id={arr2}
/>
<label
for={arr2}
>
{arr2}
</label>
</li>
)}
</div>
)
};
ReactDOM.render(<Test />, document.getElementById('app'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"> </div>
我推入 arr1
的所有内容都应该从 arr2
的映射中删除,而是返回新推入的值。这是为什么?
const [arr1, setArr1] = React.useState([]);
const arr2= ['banana', 'coconut', 'milk']
React.useEffect(() => {
initList()
}, [])
function add (t) {
setArr1(...arr1, t.currentTarget.value)
console.log('arr1: ' + arr1)
}
function initList () {
setArr1(arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 =>
<li>
<input
onChange={add}
type='radio'
name='arr1'
value={arr2}
id={arr2}
/>
<label
for={arr2}
>
{arr2}
</label>
</li>
));
}
return (
<div>
{arr1}
</div>
)
- 不要将 JSX 元素保持在状态 (arr1)。状态变量只包含数据。
- setArr1(...arr1, t.currentTarget.value) --> 这里没有设置为数组。更新为 setArr1([...arr1, t.currentTarget.value])
试试这个片段。
const Test = () => {
const [arr1, setArr1] = React.useState([]);
const arr2= ['banana', 'coconut', 'milk']
function add (t) {
setArr1([...arr1, t.currentTarget.value])
console.log('arr1: ' + arr1)
}
return (
<div>
{arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 =>
<li>
<input
onChange={add}
type='radio'
name='arr1'
value={arr2}
id={arr2}
/>
<label
for={arr2}
>
{arr2}
</label>
</li>
)}
</div>
)
};
ReactDOM.render(<Test />, document.getElementById('app'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"> </div>