简体   繁体   中英

React Native:Why does the child component have access in a variable which is inside the useEffect in a parent component?

i have the following code.I can't understand why the "TestA" component has access to the "s" variable which is inside the useEffect in "Test" component.

import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';

const Test = ({children}) => {
  const [init, setInit] = useState(0);
  useEffect(() => {
    setInit(1);
  }, []);
  useEffect(() => {
    s = {
      example: 'www',
    };
  }, []);
  // console.log(s);
  return init > 0 ? <View>{children}</View> : <Text>Noooo</Text>;
};
const TestA = () => {
  console.log(s); -->why this has access inside the useEffects' variable "s"??? 
  return (
    <View>
      <Text>Hello {s.example}</Text>
    </View>
  );
};
const App = () => {
  return (
    <>
      <Test>
        <TestA />
      </Test>
    </>
  );
};

export default App;

I notice this happen only for ReactNative.In React something like that doesn't work.Is something that babel does in react native.Here is my package.json file:

{
  "name": "exampleNative",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.11.0",
    "react-native": "0.62.2"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.58.0",
    "react-test-renderer": "16.11.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

I think this is happening because the child functional component has access to the scope of the parent functional component because it has been defined inside it. It is a concept in JavaScript called 'Closures'. You can read more about it in this blogpost (not mine). https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM