React函数式组件中箭头函数返回布尔值的提取问题
Hey there! Let's work through how to fix the issue you're having extracting the isInitJobExpanded logic from your React 16.2 stateless functional component (SFC).
First, remember that React 16.2 doesn't support Hooks yet—so all logic in your SFC has to be pure, stateless, and rely entirely on props passed into the component. Here are the most common pitfalls and fixes:
Common Reasons for Errors & Fixes
Your extracted function is missing required dependencies
If your originalisInitJobExpandedlogic relied on props or local variables in the component, you need to explicitly pass those as arguments to your extracted function. You can't let the function "reach into" the component's scope implicitly—it'll cause undefined errors or unexpected behavior.Example of wrong vs right:
// ❌ Wrong: Function tries to access component-scoped variables without params const isInitJobExpanded = () => { return job.isInit && expandedJobs.includes(job.id); // job/expandedJobs are undefined here } const JobComponent = ({ job, expandedJobs }) => { const expanded = isInitJobExpanded(); // Throws error // ... rest of component }// ✅ Right: Pure function with explicit params const calculateIsInitJobExpanded = (job, expandedJobs) => { // Add guards if needed to avoid null/undefined errors if (!job || !expandedJobs) return false; return job.isInit && expandedJobs.includes(job.id); } const JobComponent = ({ job, expandedJobs }) => { const isInitJobExpanded = calculateIsInitJobExpanded(job, expandedJobs); // ... rest of component }You're accidentally using React Hooks (which don't exist in 16.2)
If you tried to useuseStateoruseMemoin your extracted logic, that'll throw an error immediately—Hooks weren't introduced until React 16.8. If your logic needs to track state (like remembering previous expansion states), you have two options:- Lift the state up to a parent class component, and pass the necessary values/handlers down via props
- Convert your SFC to a class component, where you can manage state with
this.state
You have typos or mismatched prop names
Double-check that the props you're passing to your extracted function match exactly what's available in the component. A typo likeexpandedJobinstead ofexpandedJobswill cause "cannot read property 'includes' of undefined" errors.
Quick Debugging Tip
If you're still getting errors, log the arguments passed to your extracted function at the start:
const calculateIsInitJobExpanded = (job, expandedJobs) => { console.log('Job:', job, 'Expanded Jobs:', expandedJobs); // Check if values are what you expect if (!job || !expandedJobs) return false; return job.isInit && expandedJobs.includes(job.id); }
This will help you spot if you're passing undefined or unexpected values.
内容的提问来源于stack exchange,提问作者tgrrr

