您将如何修复或改进组件?

问题描述 投票:0回答:1
class App extends React.Component {  
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name || 'Anonymous'
    }
  }    
  render() {
    return (
      <p>Hello {this.state.name}</p>
    );  
  }
}

删除状态并通过以下实现使用道具?如果是这样你怎么做的?

getDerivedStateFromProps

或(最好)改为功能组件?

期待建议!

javascript reactjs
1个回答
5
投票

这是一个单行无状态组件:

const App = ({ name }) => <p>Hello {name || 'Anonymous'}</p>

它与您的类具有完全相同的行为

© www.soinside.com 2019 - 2024. All rights reserved.