获取错误:TypeError:当我尝试使用togglePersonsHandler渲染元素以获取personsState内的内容时,无法读取未定义的属性“ state”。目的是通过单击按钮来获取内容。
这是我的App.js文件
import React, { useState } from 'react';
import './App.css';
import Person from './person/Person';
const App = props => {
const [ personsState ] = useState({
persons: [
{ name: 'Maxmillian', age: 28 },
{ name: 'Manu', age: 18 },
{ name: 'Stephanie', age: 24 }
],
otherState: 'some other value',
showPersons: false
});
const switchNameHandler = (newName) => {
// console.log('Was clicked!');
this.setState({
persons: [
{ name: newName, age: 28 },
{ name: 'Manu', age: 18 },
{ name: 'Stephanie', age: 24 }
]
});
};
const nameChangedHandler = (event) => {
this.setState({
persons: [
{ name: 'Max', age: 28 },
{ name: event.target.value, age: 18 },
{ name: 'Stephanie', age: 24 }
]
})
};
const togglePersonsHandler = () => {
const doesShow = this.state.showPersons;
this.setState({showPersons: !doesShow});
}
const style = {
backgroundColor: 'white',
font: 'inherit',
border: '1px solid blue',
padding: '8px',
cursor: 'pointer'
};
return (
<div className="App">
<h1>Hi, I'm a React App</h1>
<p>This is really working!</p>
<button
style={style}
onClick={togglePersonsHandler}>Switch Name</button>
{
this.state.showPersons === true ?
<div>
<Person
name={personsState.persons[0].name}
age={personsState.persons[0].age} />
<Person
name={personsState.persons[1].name}
age={personsState.persons[1].age}
click={switchNameHandler.bind(this, 'Max!')}
changed={nameChangedHandler}>My Hobbies: Racing</Person>
<Person
name={personsState.persons[2].name}
age={personsState.persons[2].age} />
</div> : null
}
</div>
);
}
// ein Element entwickeln
// return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Work'));
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
这里是Person.js
import React from 'react';
import './Person.css';
const person = (props) => {
return (
<div className="Person">
<p onClick={props.click}>I'm {props.name} and I am {props.age} years old. </p>
<p>{props.children}</p>
<input type="text" onChange={props.changed} value={props.name} />
</div>
)
};
export default person;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
感谢您的支持!
答案 0 :(得分:2)
this.state
和this.setState
仅在扩展React.component
的类组件中可用。您正在使用功能组件,因此需要使用钩子来更新状态。我建议为showPersons
创建一个单独的状态:
const [ showPersons, setShowPersons ] = useState(false);
const togglePersonsHandler = () => {
setShowPersons(!showPersons);
}
如果只需要一个状态,请添加一个setter:
const [ personsState, setPersonsState ] = useState({...});