我试图理解下面的代码,它来自 Redux 示例 TODOMVC , 可以用类符号来写。 代码是
const App = ({todos, actions}) => (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
我尝试了以下但它不起作用,我得到 Warning: App(...): When calling super() in
App, make sure to pass up the same Prop 你的组件的构造函数被传递。
class App extends React.Component {
constructor({todos, actions}) {
super({todos, actions});
this.todos = todos;
this.actions = actions;
}
render() {
return(
<div>
<Header addTodo={this.actions.addTodo} />
<MainSection todos={this.todos} actions={this.actions} />
</div>
)
}
}
最佳答案
传递给 App
的是 props
。 ({ todos, actions })
只是从 props
解构。这应该有效:
class App extends React.Component {
render() {
const { todos, actions } = this.props;
return(
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
)
}
}
通过在构造函数中设置 this.todo = todos
,您将设置一个实例级别的属性。这意味着如果 props 稍后更改,Header
和 MainSection
将不会更新。
关于javascript - 这个 React 代码如何转换为类表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49341321/