我想要一点代码智慧,而不是修复。我以一种方式学习了react,并且我看到了不同格式的代码。我在试着了解它们之间的区别。
我得到了这个jsx代码片段:
import React from 'react'
import { Route, Redirect } from 'react-router'
import { connect } from 'react-redux'
import * as reducers from '../reducers'
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
const mapStateToProps = (state) => ({
isAuthenticated: reducers.isAuthenticated(state)
});
export default connect(mapStateToProps, null)(PrivateRoute);
代码运行得很好,但我正在尝试理解它。我学到的课程是以班级为基础的。
例如:
class Logout extends Component {
componentDidMount() {
this.props.dispatch(logout());
}
render() {
return(<Redirect to="/" push={true} />);
}
}
关于这段代码,我有两个问题:
这看起来是一个函数,是真的吗?,,
,
如果代码应该是一个类,并且我可以看到它应该是什么样子,那么我就知道如何将其余的代码转换为正确的代码。
谢谢
发布于 2018-06-10 04:59:33
import React from 'react'
import { Route, Redirect } from 'react-router'
import { connect } from 'react-redux'
import * as reducers from '../reducers'
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
const mapStateToProps = (state) => ({
isAuthenticated: reducers.isAuthenticated(state)
});
export default connect(mapStateToProps, null)(PrivateRoute);
这是一个功能组件。您也可以将其称为无状态组件。
这也可以写成基于类的组件/有状态组件,如下所示:
import React from 'react'
import { Route, Redirect } from 'react-router'
import { connect } from 'react-redux'
import * as reducers from '../reducers'
class PrivateRoute extends React.Component {
render() {
return (
<Route {...rest} render={() => (
isAuthenticated ? (
<Component {...this.props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}}/>
)
)}/>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: reducers.isAuthenticated(state)
});
export default connect(mapStateToProps, null)(PrivateRoute);
选择明智地使用函数式和基于类的组件。因为基于类的组件更重,因为它们有生命周期挂钩和状态,而功能组件只是业务逻辑。
我个人使用的是什么?
我遵循这个模式。我将我所有的呈现逻辑放在小的功能组件中,所有的业务逻辑放在一个基于类的组件中,它将成为功能组件的父组件。
下面是一个示例:
TestContainer.js
class TestContainer extends React {
// state
// lifecycle hooks
// events
// other functions
render() {
return <Test />; // pass any props here in Test
}
}
export default TestContainer; // connect with redux store here (if you want)
Test.js
const Test = props => (
// rendering logic
);
export default Test; // don't connect to redux store here. if you want something from redux store, then connect the parent to redux store and get data from parent(TestContainer) as props.
https://stackoverflow.com/questions/50778377
复制相似问题