我有以下react功能组件来帮助支持react路由器所需的身份验证路由。
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location }
}}/>
)
)}/>
)
我需要将其从功能组件转换为类组件,以便利用React.component的componentDidMount方法。不幸的是,我很难弄清楚如何迁移它。如果我照原样做,我需要复制组件和…rest参数,但我不知道怎么做。我想我可以用这个.props.Component获得组件参数,但我不确定如何拉…rest。我是JSX和ES6的新手,因此非常感谢任何帮助或指导。
@Sulthans的回答是正确的,直接回答了您的问题。但我想用一种不同的方式给出答案,并提出一个建议。
根据您的问题,您的需求类似于在功能组件中使用生命周期挂钩(即componentDidMount
)。
我建议继续使用功能组件,并使用useffect
实现挂钩,如果您使用的是最新的react
useEffect(() => {
console.log('mount it!');
}, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour
由于以下原因,我建议这样做
一个漂亮的,干净的重构通过扩展路由
组件:
class PrivateRoute extends Route {
render() {
return isAuthenticated()
? super.render()
: <Redirect to={{
pathname: '/login',
state: {from: props.location}
}}/>;
}
}
如果你使用这个,你必须包装你的
<Router>
<Navbar/>
<SideDrawer/>
<Switch>
<Route path="/tokens" component={Login}/>
<PrivateRoute exact path="/" component={ExampleComponent}/>
<PrivateRoute path="/users" component={Users}/>
<PrivateRoute path="/software" component={Software}/>
</Switch>
</Router>
函数组件是渲染
函数,因此:
class PrivateRoute extends React.Component {
render() {
const {component: Component, ...rest} = this.props;
return (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location }
}}/>
)
)}/>
);
}
}
或者,写得更易读一点:
class PrivateRoute extends React.Component {
render() {
const {component: Component, ...rest} = this.props;
const renderRoute = props => {
if (isAuthenticated()) {
return (
<Component {...props} />
);
}
const to = {
pathname: '/login',
state: {from: props.location}
};
return (
<Redirect to={to} />
);
}
return (
<Route {...rest} render={renderRoute}/>
);
}
}
我试图将我的类组件转换为功能组件,但我的过滤器不再工作了。 主要的错误是当我想转换listProducts因为我不知道如何定义与useState为这种情况下的preState 如何能为情况更新状态? 这是我的密码 类组件 功能成分
我有一个应用程序正在使用类组件开发react,我发现了一个功能的代码,我想添加到我的代码中,但它是使用功能组件制作的。代码在这里https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8 但相关部分是这样的。 我不知道如何在我的类组件中添加那个控件变量 我应该把它添加到我的州吗?我不明白如何让它在类组件中工作
我是ES6新手。在编写React组件的不同方法上有点困惑。我从“react.createClass”开始,然后使用ES6类语法移到“extends react.component”。
react 在 A 函数设置了state 然后调用 B函数,B函数中使用了state,但直接获取state不是最新值。 使用Effect和通过函数参数传递来解决,感觉都不优雅,大佬们有没有比较好的经验?
我想将web设计师用纯HTML编写的复杂div容器转换为React组件。此div容器具有React to manage的状态。我知道我可以将div转换为JSX,但这意味着设计师和我都要加倍努力。危险的是,Html不处理状态。我可以创建React的子类。组件,定义状态并在不使用JSX的情况下将状态值呈现到div容器中? 下面是div容器标记的一个片段:
问题内容: 我在一个一维数组中有一个例子。它只会输出列。我的想法是使用2d数组选择行和列。这是我的代码: myfile.csv 输出: 名字蒂姆汤姆 问题答案: 我只是将split结果()添加到a中,如果您确实希望将其作为2d数组,则在事后将其转换。