【发布时间】:2020-11-14 16:45:01
【问题描述】:
我为找工作做了简单的任务。使用 react 和 redux。当我从输入中获得价值并将它们发送到减速器时,它们就会迷路。等等,没那么容易。 reducer 获取的第一个项目获取道具名称、年龄、类型、索引并返回新状态。好的。但其他物品在途中丢失了道具名称和年龄。什么?他们是怎么做到的? Reducer 返回空 obj 进行渲染。不要在 dispatch 中看 obj,我会返工。
减速器
case 'EDIT_ITEM':
console.log(action.name, action.age, action.id);
return state.map((item, index) =>
action.id === index
? {
name: action.name,
age: action.age
}
: item
);
App.js
function EditUsers() {
const listItems = users.map(function (value, index) {
return (
<form>
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text">{value.name}, {value.age}</span>
</div>
<input type="text" placeholder="New name" id="newName" className="form-control"/>
<input type="text" placeholder="New age" id="newAge" className="form-control" aria-describedby="button-addon2"/>
<div className="input-group-append">
<button onClick={() => dispatch({
type: 'EDIT_ITEM',
id: index,
name: document.getElementById('newName').value,
age: document.getElementById("newAge").value
})}
className="btn btn-outline-primary"
type="button"
id="button-addon2">
Изменить
</button>
</div>
</div>
</form>
)
});
return (
<div>{listItems}</div>
)
}
【问题讨论】:
-
您不应该使用
document.getElementById来获取输入值。在反应中,您应该使用controlled component 来管理输入值。 -
或者,您可以保持输入不受控制,使按钮的类型为“提交”并将逻辑移动到表单的
onSubmit回调并使用提交事件来访问表单字段。 -
我不知道 Hooks 是什么样子的,我如何从输入中获取价值?
e.target.name.value或this.input.name.value? -
e.target.value就足够了。e.target指向事件发生的 DOM 元素,所以e.target.value是字段中的值