【发布时间】:2021-04-05 10:58:26
【问题描述】:
我想要调用一个 API,具体取决于从我的功能组件的下拉列表中选择的值。我在函数组件之外定义了一个函数,它接受参数并调用 API。我正在使用 useState 挂钩来存储在 action_name 状态值中选择的值。但该状态在 callSomeAPI 函数中不可用。我应该在我的组件中移动 callSomeAPIfunction 吗?它甚至是一种有效的方法吗?
function callSomeAPI(container_name) {
console.log(container_name);
action_name = event.target.value;
let e = document.getElementById("actions")
console.log(e.target)
action_name = e.target
fetch(<some_url>, {
method: 'PUT',
})
.then(response => console.log(response.json()))
.catch(console.log("error problem in api request"));
e.preventDefault();
}
export function AlertsRenderer(props) {
const [action_name, callSomeAPI] = useState(null);
return (
<table>
<tr>
<th> Column1 </th>
<th> Column2 </th>
<th> Column3 </th>
<th> Button </th>
<th> Actions </th>
</tr>
{props.alerts.map(alert => (
<tr key={alert.id.toString()}>
<td>{alert.data1}</td>
<td>{alert.data2}</td>
<td>{alert.data3}</td>
<td>
<button value={alert.id} onClick={() => markAsSolved(alert.id)}>Mark as solved</button>
</td>
<td>
<select defaultValue={action_name} onChange={() => callSomeAPI(alert.data1)} name="actions" id="actions">
<option hidden disabled selected value>Select an action</option>
<option value="inc-disk">Increase disk size</option>
<option value="restart-php">Restart PHP</option>
</select>
</td>
</tr>
))}
</table>
);
}
【问题讨论】:
-
你在这里做的很奇怪。您需要一个将所选值作为参数的 callSomeAPI 函数。不要从 DOM 中获取它。使用受控选择。
标签: reactjs react-hooks