反应:应该在子组件时间获取 url,还是应该在祖先中获取一次,然后作为道具逐层传递?



我有一个祖先组件,还有一个Name组件,它是Index的第4代子组件。我必须向此应用程序添加一个新功能,使 Name s 为红色或粗体,或者根据 url 参数添加一些前缀,例如"&red=true&bold=true&prefix=true

"。我真的厌倦了逐层传递单个道具,因为我必须逐层添加"propA={this.props.propA}",如果有新的参数,则逐层再添加。

或者也许我应该传递所有道具,我不喜欢,这意味着逐层传递所有道具。

第三种方法是在 Name 组件构造函数本身中获取 url 参数,然后,一个完成,全部完成。但是,它会在每个名称初始化作用域中获取 url 参数,所以这会很多,我担心性能或我的方式逻辑不正确。

那么,哪种方式更好:

1 逐层传递单个道具,如果有新的道具要逐层传递,则添加道具传递。 2 逐层传递所有道具。 3 在将使用它的最小组件中获取 URL 参数。

还是有其他方法?

谢谢。

索引.js

class Index extends React.component {
render() {
return <A />
}
}
ReactDOM.render(
<Index/>,
document.getElementById("App")
);

答.js

class A extends React.component {
render() {
return <B />
}
}

B.js

class A extends React.component {
render() {
return <C />
}
}

C.js

class A extends React.component {
render() {
return <Name />
}
}

名称.js

class Name extends React.component {
construtor(props){
super(props);
this.name = null;
this.namePrefix = getUrlParam(window.location.search).nameprefix //boolean
}
render() {
if (this.namePrefix) {
this.name = 'The Genius ' + 'Jack';
}
else {
this.name = 'Jack';
}
return <div>{this.name}<div>
}
}

使用 MobX 或新的 React Context API,你可以让选定的项目可用于整个 DOM 树,任何需要某些属性的组件都可以订阅它们。

https://reactjs.org/docs/context.html

https://mobx.js.org/getting-started.html

这是应用程序中应该考虑引入Redux(或Flux(的地方。简而言之,每个组件都能够触发从保存应用程序所有数据的唯一存储中获取数据的操作。props 将从根组件向向组件树,每个组件都可以随时"请求"数据,触发从后端获取数据或通过 props 提取数据的操作。

更多关于 Redux : https://redux.js.org/introduction

最新更新