当尝试删除每个项目时,React 使用 Hook 设置状态未定义
2020-01-09
2243
我使用 React Hooks,在“setPersonsState”上的“deletePersonHandler”函数中未定义。 在教程中使用“this.setstate”可以删除每个项目,但是当我尝试时 所有数据都被删除并且没有返回。 当我看到日志“setPersonsState”'undefined' 用这个解决了
但仍然无法设置该状态,
Person.js
<div className="Person">
<p>I'm a {props.name} I am {props.age} years old! {props.children}</p>
<button onClick={props.click}>{props.name} index: {props.indexData}</button>
<input type="text" onChange={props.changed} value={props.name} />
</div>
App.js
// React hooks
const App = () => {
// state
// array destructuring
const [personsState, setPersonsState] = useState({
persons: [
{ name: 'Max', age: 28 },
{ name: 'Manu', age: 29 },
{ name: 'Stephanie', age: 30 }
],
otherState: [{ phone: '+628762663994' }],
showPersons: true,
});
//Event onClick
const deletePersonHandler = (personIndex) => {
const persons = personsState.persons;
persons.splice(personIndex, 1);
setPersonsState({ persons: persons });
console.log(persons);
console.log(setPersonsState({ persons: persons }));
};
// End Event
//element
let persons = null;
if (personsState.showPersons) {
persons = (
<div>
{personsState.persons.map((person, index) => {
return <Person
click={() => deletePersonHandler(index)}
indexData={index}
name={person.name}
age={person.age}
changed={(setNameChange) => nameChangeHandler(setNameChange)} />
})}
</div>
);
}
//end element
return (
<div className="App">
<h1>Hello React</h1>
<button className="button-cus"
// onClick={() => switchNameHandle('Button')}>Switch Name</button>
onClick={() => tooglePersonsHandler()}>Toogle Name</button>
{persons}
</div >
);
}
3个回答
尝试一下并检查实时 https://vvhoy.csb.app/
const deletePersonHandler = item => {
console.log(item);
let filtered = personsState.persons.filter(
person => person.age !== item.age
);
setPersonsState({ ...personsState, persons: filtered });
};
传递完整对象
deletePersonHandler(person)
<div>
{personsState.persons.map((person, index) => {
return <Person
click={() => deletePersonHandler(person)}
indexData={index}
name={person.name}
age={person.age}
changed={(setNameChange) => nameChangeHandler(setNameChange)} />
})}
</div>
akhtarvahid
2020-01-09
将此通道 const persons = personsState.persons; 替换为 const persons = [...personsState.persons]; 您需要包含先前的状态,例如 setPersonsState({...personsState, persons}) 或删除导致 if 为 false 的 showPersons 状态
David Desjardins
2020-01-09
const deletePersonHandler = (personIndex) => {
//dont use splice because react state must be immutable
setPersonsState({
persons: personsState.persons.slice(0, index).concat(personsState.persons.slice(index + 1)),
otherState: personsState.otherState,
showPersons: personsState.showPersons
});
};
希望它能起作用
Man
2020-01-09