【发布时间】:2021-04-04 13:25:52
【问题描述】:
我正在用 React.JS 开发一个应用程序
我需要在插入之前添加一个条件。
代码:
const App = () => {
const [item, setItem] = useState([])
const [category, setCategory] = useState([])
const categories = category.map(elem => ({
value: elem.id,
label: elem.cat,
}));
const [category_select, setCategorySelect] = React.useState(null);
function handleChangeCategory(value) {
setCategorySelect(value);
}
useEffect(() => {
getItems()
}, [])
useEffect(() => {
getCategories()
}, [])
const getItems = async () => {
const response = await axios.get(REQUEST_1)
setItem(response.data)
}
const getCategories = async () => {
const response = await axios.get(REQUEST_2)
setCategory(response.data)
}
const addItems = () => {
axios.post(`${REQUEST_1}`, {cat: category_select.value});
};
const body = () => {
return item && item.map((elem,j) => {
return (
<tr key={elem.id}>
<td><span>{elem.cat}</span></td>
</tr>
)
})
}
return (
<>
<div>
<div>
<div>
<div>
<NoSsr>
<Select
classes={classes}
styles={selectStyles}
inputId="category"
TextFieldProps={{
label: 'Category',
InputLabelProps: {
htmlFor: 'category',
shrink: true,
},
placeholder: 'Category...',
}}
options={categories}
components={components}
value={category}
onChange={handleChangeCategory}
/>
</NoSsr>
<span>Select</span>
</div>
<div>
<label> </label>
<span onClick={addItems}></span>
</div>
</div>
<div>
<div>
<div>
<table>
<thead>
<tr>
<th>
<span>Category</span>
</th>
</tr>
</thead>
<tbody>
{body()}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default App;
想法是检查要插入的项目是否已经存在,如果已经插入,则通过弹出窗口显示消息。
如何在const addItems = () => {...} 和弹出窗口中添加此条件?我必须把那个条件放在这里吗?
我该怎么做,建议?
【问题讨论】:
标签: javascript arrays json reactjs api