我是新来反应钩子的人,我很难转换此类, 使用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);
答案 0 :(得分:3)
一些最常用的钩子是useState
,useEffect
。 useState在某些方面类似于setState,区别之一是您没有useState的回调功能。您可以使用useEffect实现类似的效果。 useEffect
可以用作componentDidMount
,componentDidUpdate
和componentWillUnmount
。如果传递一组空的依存关系[]
(如以下示例所示),则其行为与componentDidMount
相同。如果您希望基于某些条件(例如,正在更新的状态)来触发特定功能,则可以将其作为dependancy
传递。然后,useEffect
表现为componentDidUpdate
。 useEffect
接受第三个参数作为回调函数。在卸载组件时触发此操作,从而增加了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);
答案 1 :(得分:1)
您可以像这样重写钩子。
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