我需要从原始数组props.ids
获得一个数组,并有条件地(如果不是NULL)附加变量selectedId
。以下内容有效,但语法看起来不正确。我需要selectedId &&
来检查非NULL,如果是,请添加selectedId
。这个小表达式有更好的语法吗?
const [selectedId, setSelectedId] = useState(null);
obj = {
'exclude':[...props.ids, selectedId && selectedId]}
}
以单行方式
const [selectedId, setSelectedId] = useState(null);
obj = {
exclude:[...props.ids, ...(selectedId === null ? [] : [selectedId])]}
}
正确方式
const [selectedId, setSelectedId] = useState(null);
obj = {
exclude: [...props.ids]
}
if (selectedId !== null) {
obj.exclude.push(selectedId)
}
除了Ananth的答案外,您还可以使用三元运算符内联
const ids = [1, 2, 3];
let item = null;
let resultWhenNull = [...ids, ...(item ? [item] : [])];
console.log(resultWhenNull);
item = 4;
const resultWhenNonNull = [...ids, ...(item ? [item] : [])];
console.log(resultWhenNonNull);
您可以使用三元运算符或简单的if语句来完成此
const [selectedId, setSelectedId] = useState(null);
const obj = {};
// if selectedId is present append selectedId, else return array of props.ids
obj['exclude'] = selectedId ? [...props.ids, selectedId] : [...props.ids]
const value = false;
const props = [1, 2, 3];
const valToAppend = 4;
const obj = {};
obj['test'] = value ? [...props, valToAppend] : [...props];
console.log(obj);