我在服务器上渲染React。
我有一个由三个组件组成的公用链。我需要将一个units
对象(就是普通的js对象{name: 'example.com'}
)从最外层的组件<Foo />
传递到链中最深的组件<FooBox />
。现在,我必须将我的unit
对象作为this.props.units
传递给每个组件。我看起来不是很好,这看起来像是一些糟糕的做法:
// my-react-components.js file
var FooBox = React.createClass({
render: function() {
return (
<div>
// here I pass 'units'
<FooList data={this.props.data} units={this.props.units}>
</div>
);
}
});
var FooList = React.createClass({
render: function() {
return (
<div>
// and here I pass 'units'
<Foo myId={this.props.data[0]} units={this.props.units} />
</div>
);
}
});
var Foo = React.createClass({
render: function() {
var units = this.props.units; // and only here I use `units`
return (
// only here I need `units`
<div dangerouslySetInnerHTML={{__html: units[this.props.myId].name}}>
</div>
);
}
});
在服务器端,我的代码如下(一个Node.js应用程序):
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var FooBox = require('../my-react-components.js');
var data = [...some data here...];
var units = {name: 'example.com'}; // this is my 'units' object
var html = ReactDOMServer.renderToString(React.createElement(FooBox, {
data: result,
units: units // so 'units' comes yet from here
}));
我的问题是:
这是在<Foo />
中获取units
的唯一方法吗?仅仅通过将其作为props
传递到整个链条上?有没有一种方法可以让<Foo />
中的units
更容易,避免一步一步地传递props
?
发布于 2015-12-18 11:11:26
您可以使用context而不是props.It,这使您可以通过组件树传递数据,而不必在每个级别上手动传递道具https://facebook.github.io/react/docs/context.html
发布于 2015-12-18 11:21:34
为了快速向下传递{...this.props}
。为了清晰的逻辑,我认为我们必须把它传递下去
发布于 2015-12-18 12:24:32
在我看来,在组件层次结构树下大量地重新声明和重新分配相同的属性是React更令人恼火的特性之一。有人可能会说,这是一个优势:数据流是明确的,并使您的应用程序易于推理。但就我个人而言,我发现这样的重复是不和谐的。
当然,正如vistajess所提到的,上下文是一种解决方案。但是我不愿意在一个实验性的API上投入太多。
另一种解决方案是使用Flux,并让存储侦听器分布在不同的组件中。(例如,在Redux中,这些将是连接的组件。)当然,这在一定程度上增加了组件的复杂性。
或者最终你可以笑着忍受它。(我通常就是这么做的。)不断地重复输入相同的属性可能会很烦人,但就代码的味道而言,这是相当次要的。也请记住,React仍然是相当新的,它的API正在快速发展。假以时日,这个问题肯定会有一些解决方案。(也许是上下文的主流?)就目前而言,React的弱点远远大于其优势,这一事实令人欣慰。
https://stackoverflow.com/questions/34347765
复制相似问题