Kiedy używam tego kodu :
onChange = e => {
const { name, value } = e.target;
this.setState(currentState => ({
tempInput: { ...currentState.tempInput, [name]: value }
}));
};
Wszystko działa dobrze, ale kiedy to robię:
onChange = e => {
this.setState(currentState => ({
tempInput: { ...currentState.tempInput, [e.target.name]: e.target.value }
}));
};
Otrzymuję błąd: TypeError: e.target jest null, jaka jest różnica? czy czegoś mi brakuje?
2
Alexander
5 listopad 2018, 23:55
1 odpowiedź
Najlepsza odpowiedź
Ponieważ this.setState()
to asynchronous
. Więc e
staje się niezdefiniowany, gdy jest wykonywany.
Aby to złagodzić, możesz zdestruować e
w parametrach funkcji onChange
, które utrzymują zdefiniowane name
i value
w zakresie funkcjonalnym onChange:
onChange = ({ target: { value, name } }) => {
this.setState(currentState => ({
tempInput: { ...currentState.tempInput, [name]: value }
}));
};
Lub... możesz zniszczyć e.target
przed wykonaniem this.setState()
, które również utrzymuje name
i value
zdefiniowane w zakresie funkcjonalnym onChange
:
onChange = e => {
const { name, value } = e.target;
this.setState(currentState => ({
tempInput: { ...currentState.tempInput, [name]: value }
}));
};
4
Matt Carlotta
6 listopad 2018, 00:25
Podobne pytania
Nowe pytania
reactjs
React to biblioteka JavaScript do tworzenia interfejsów użytkownika. Wykorzystuje deklaratywny paradygmat oparty na komponentach i ma być zarówno wydajny, jak i elastyczny.