我最近编写了 React 代码,使用 this.props
似乎太冗长了,所以我用 google 搜索了一些文章,想出了如何做到这一点并尝试编写代码。
class MyComponent extends Component {
// the usual way
render() {
return <div>{this.props.value}, {this.props.value2}</div>
}
}
class MyComponent extends Component {
// the way of avoding this.props
render({value, value2}){
return <div>{value}, {value2}</div>;
}
}
class ParentComponent extends Component {
render(){
return <myComponent value={1} value2={2} />
}
}
我不知道这是如何在内部处理的,所以我尝试在 https://babeljs.io/repl 处进行转译但是仍然很难理解这些语法有哪些优点和缺点。
这里是问题的总结:
- 使用解构来减少代码是个好主意吗?
- 如果不行,不知为何不好用。
最佳答案
除了使对所述变量的引用更短之外没有任何好处。换句话说,更少的输入和更好的可读性。
有关更多信息,请查看 this page on MDN :
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
这里有一些其他的例子,我发现它们更常见:
无状态功能组件中的解构:
const MyComponent = ({value, value2}) => (
<div>{value}, {value2}</div>
);
ReactComponent 类中的解构:
class myComponent extends Component {
render(){
let {value, value2} = this.props;
return <div>{value}, {value2}</div>;
}
}
对于有状态组件,您可以对状态变量执行相同的操作。
关于javascript - 具有破坏语法和普通空参数的渲染函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150315/