我可以动态导入组件
library(dplyr)
setdiff2 <- function(x, y) y[!y %in% x]
dt %>%
group_by(user_id) %>%
mutate(sku = as.character(sku),
NNSP = lengths(Reduce(setdiff2, strsplit(sku,'-'), accumulate = TRUE)),
Tot_NNSP = cumsum(NNSP))
如何将道具传递给组件? 我将组件传递给路由器:
let that = this
import('./pathToMyComponent').then(component => {
// how to pass props to the component here?..
that.setState({myModule : component.default})
})
谢谢。
更新:
我设法解决了这个问题:
<Route path='myPath' component={this.state.myModule}/>
然后使用函数:
import('./pathToMyComponent').then(component => {
that.setState({myModule : component.default})
})
答案 0 :(得分:1)
您需要使用React.lazy或react-loadable之类的东西,这是React文档中的示例:
Ptt bat$depth Latitude Longitude area
88734 -500 -18.0490 -38.9485 AR
88734 -750 -19.4095 -39.4320 AR
88734 -800 -19.8043 -40.5436 AR
88734 -490 -20.0543 -40.9095 AR
88734 -300 -21.4085 -41.0954 AR
129041 -1500 -25.0954 -50.4350 AR
129041 -2400 -26.4095 -51.0954 AR
129041 -1200 -27.5309 -51.9053 AR
129041 -1190 -27.7953 -52.5403 AM
129041 -1606 -28.0904 -51.9504 AM
120941 -2000 -29.4985 -52.0590 AM
更多信息在这里:
react.lazy:
https://reactjs.org/docs/code-splitting.html
可加载的内容:
答案 1 :(得分:1)
正如其他人所述,React.lazy是动态导入组件的方式,同时仍可以在代码中使用它。。这意味着,您不必使用.then(component => { that.setState ... )}
逻辑。
如果要将道具传递到路线,可以执行以下操作:
<Route exact path="/somepath" render={props => <Test {...props} addedProp={val} />} />
我使用类似的组件将道具注入路线:(此特定示例将先前的路径路径添加到道具中,但从技术上讲,您可以在此处注入任何想要的道具)
export default withRouter(
class AppBrowserRouterRoutes extends React.Component {
state = {
referrer: ""
}
componentDidUpdate(prevProps) {
if (this.props.location.pathname !== prevProps.location.pathname) {
this.setState({
referrer: prevProps.location.pathname
})
}
}
// Inject old route data into existing props so we can see where we came from
addStateToProps = (existingProps) => {
return {
...existingProps, // existing props
...this.state // old route data
}
}
render() {
return (
<Switch>
<Route exact path="/" render={props => <AppHomePage {...this.addStateToProps(props)} />} />
<Route exact path="/companies" render={props => <AppCompanies {...this.addStateToProps(props)} />} />
</Switch>
);
}
}
)
答案 2 :(得分:0)
也许我有类似的情况,我需要在 Click 上加载组件并将道具或参数传递给它
这是我的解决方法
DynamicComponent.js
import React from 'react';
const DynamicComponent = (props, params) => {
console.log(params);
console.log(props);
return (
<h4>May Dynamic {params}</h4>
);
};
export default DynamicComponent ;
ParentComponent.js
import React, {useState} from 'react';
const ParentComponent= (props) => {
const [module, setModule] = useState(null)
const handleClick = () => {
let params = { userID: 123 };
import('./DynamicComponent.js').then((c) => {
setModule(c.default(props, params)); // send props or params here
});
};
return (
<div>
<h4>parens{params}</h4>
<button type="button" onClick={handleClick}>Load Dynamic Component</button>
{/* Render dynamic component here */}
{ module ? (
<div>{module}</div>
) : null }
</div>
);
};
export default DynamicComponent ;