将react中的基类组件转换为钩子



我是react hook的新手,很难转换这个类,转换为具有ES6语法的react钩子。有人能帮帮我吗?这是我的名片。。。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchMovie, setLoading } from '../../actions/searchActions';
import Spinner from '../layout/Spinner';
export class Movie extends Component {
componentDidMount() {
this.props.fetchMovie(this.props.match.params.id);
this.props.setLoading();
}
render() {
const { loading, movie } = this.props;
let movieInfo = (
<div className="container">
jsx......
</div>
);
let content = loading ? <Spinner /> : movieInfo;
return <div>{content}</div>;
}
}
const mapStateToProps = state => ({
loading: state.movies.loading,
movie: state.movies.movie
});
export default connect(
mapStateToProps,
{ fetchMovie, setLoading }
)(Movie);

一些最常用的钩子是useStateuseEffect。useState在某些方面与setState相似,其中一个区别是您没有useState的回调功能。你可以使用useEffect来实现类似的效果。useEffect可以作为componentDidMountcomponentDidUpdatecomponentWillUnmount工作。如果传递一组空的依赖项[](如以下示例所示(,则其行为与componentDidMount相同。如果您希望根据某些条件(如正在更新的状态等(触发特定功能,则可以将其作为dependancy传递。然后,useEffect表现为componentDidUpdateuseEffect接受第三个参数作为回调函数。这是在组件卸载时触发的,从而添加componentWillUnmount行为。

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchMovie, setLoading } from '../../actions/searchActions';
import Spinner from '../layout/Spinner';
const Movie = () => {
useEffect(() => {
props.fetchMovie(props.match.params.id);
props.setLoading();
}, [])
const { loading, movie } = props;
let movieInfo = (
<div className="container">
jsx......
</div>
);
let content = loading ? <Spinner /> : movieInfo;
return <div>{content}</div>;
}
const mapStateToProps = state => ({
loading: state.movies.loading,
movie: state.movies.movie
});
export default connect(
mapStateToProps,
{ fetchMovie, setLoading }
)(Movie);

您可以重写为这样的钩子。

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchMovie, setLoading } from '../../actions/searchActions';
import Spinner from '../layout/Spinner';
export const Movie = ({ match}) => {
const dispatch = useDispatch();
const movie = useSelector(state => state.movies.movie);
const loading = useSelector(state => state.movies.loading);
useEffect(() => {
dispatch(fetchMovie(match.params.id));
dispatch(setLoading());
}, []);
return (
<div>
{
loading 
? <Spinner /> 
: <div className="container">
jsx......
</div>
}
</div>
)
}

使用空数组作为参数的useEffect与componentDidMount类似。我将连接更改为useSelector和useDispatch

相关内容

  • 没有找到相关文章

最新更新