React16+Redux中如何替换即将废弃的componentWillReceiveProps处理状态变更
Hey there! Great question—since componentWillReceiveProps is officially deprecated, we’ve got two solid, modern React approaches to replicate your logic without relying on outdated lifecycle methods. Let’s walk through them:
1. For Class Components: Use componentDidUpdate
The componentDidUpdate lifecycle method triggers right after your component updates (when props or state change), making it perfect for comparing previous and current props. Here’s how to adapt your code:
componentDidUpdate(prevProps) { // First, check if the job status actually changed to avoid unnecessary runs if (prevProps.job.status !== this.props.job.status) { // If the new status is 'approved', trigger the redirect if (this.props.job.status === 'approved') { this.props.history.replace('somewhere'); } } }
Pro tip: Always include a condition to compare previous and current props (like we did with prevProps.job.status !== this.props.job.status). This prevents infinite loops that can happen if your redirect causes the component to re-render repeatedly.
2. For Functional Components: Use the useEffect Hook
If you’re working with functional components (the modern React standard), the useEffect hook lets you run side effects (like redirects) when specific dependencies change. Here’s the implementation:
First, if you’re using React Router, you can grab the history object with the useHistory hook:
import { useEffect, useHistory } from 'react-router-dom'; function YourComponent({ job }) { const history = useHistory(); useEffect(() => { // Trigger redirect when job status updates to 'approved' if (job.status === 'approved') { history.replace('somewhere'); } }, [job.status, history]); // Only re-run this effect if these values change // Rest of your component logic... }
If you’re already receiving history as a prop, you can simplify it a bit:
import { useEffect } from 'react'; function YourComponent({ job, history }) { useEffect(() => { if (job.status === 'approved') { history.replace('somewhere'); } }, [job.status, history]); // ... }
Key note: The dependency array ([job.status, history]) is critical here—it tells React to only run this effect when either the job status or the history object changes. This keeps your code efficient and avoids unnecessary side effects.
Both of these approaches are fully supported by React’s current standards and will work reliably for your use case.
内容的提问来源于stack exchange,提问作者Jamie Aden

