运行底部所附的示例时,我得到了以下错误:
react-dom.development.js:49 Uncaught Error: Hooks can only be called inside the body of a function component.
at invariant (react-dom.development.js:49)
at resolveCurrentlyRenderingFiber (react-dom.development.js:11633)
at useReducer (react-dom.development.js:11830)
at Object.useState (react-dom.development.js:11824)
at Object.useState (react.development.js:2574)
at App.render (<anonymous>:25:35)
at finishClassComponent (react-dom.development.js:14466)
at updateClassComponent (react-dom.development.js:14429)
at beginWork (react-dom.development.js:15233)
at performUnitOfWork (react-dom.development.js:17940)
class App extends React.Component {
render() {
const [name, setName] = React.useState('Mary');
const [age, setAge] = React.useState(10);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
}
ReactDOM.render(
<div>
<App />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
类组件中不支持钩子,您应该将其作为一个功能组件,或者如果您仍然依赖某些类组件功能,则完全不使用钩子。
function App() {
const [name, setName] = React.useState('Mary');
const [age, setAge] = React.useState(10);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
ReactDOM.render(
<div>
<App />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
您也可以使用类似:
class App extends React.Component {
renderApp() { // function within class component
const [name, setName] = React.useState('Mary');
const [age, setAge] = React.useState(10);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
render() {
return this.renderApp()
}
}
如果你想渲染其他东西,这将更有帮助,也有助于使用其他生命周期挂钩:
render() {
return (
<div>
<h1>My App</h1>
{ this.renderApp() }
</div>
)
}