无法在 React 功能组件中设置状态

时间:2021-02-28 20:12:24

标签: reactjs typescript react-native

我是 React 和函数式组件的新手,我想创建一个简单的应用程序,其中有一个 Gallery 组件显示在应用程序中,然后我有一个应该设置的按钮状态并将其传递给组件,这是它的外观:

const App = () => {
  const [images, setImages] = useState([]);

  return (
    <ScrollView>
        <View style={styles.body}>
            <Button title="Press me" onPress={start} />
            <Gallery imgs={images}/> // Using the state here
        </View>
    </ScrollView>
  );
};

const start = () => {
  // Create images array here
  setImages(images); // [ReferenceError: Can't find variable: setImages]
};

export default App;

但我收到以下错误:[ReferenceError: Can't find variable: setImages],但 setImages 变量是在同一个文件中定义的,所以我不明白可能是什么问题。

不确定是否重要,但我正在使用 TypeScript。

2 个答案:

答案 0 :(得分:4)

状态在组件内部维护(声明、设置和使用)。使用状态的函数也需要在组件内部:

const App = () => {
  const [images, setImages] = useState([]);

  const start = () => {
    // Create images array here
    setImages(images);
  };

  return (
    <ScrollView>
        <View style={styles.body}>
            <Button title="Press me" onPress={start} />
            <Gallery imgs={images}/> // Using the state here
        </View>
    </ScrollView>
  );
};

export default App;

基本上,如果变量在函数内部声明,其作用域仅限于该函数。

答案 1 :(得分:1)

David 的回答是正确的,但是如果函数需要在组件之外,您可以将所有需要的变量作为参数传递,例如

const App = () => {
  const [images, setImages] = useState([]);

  return (
    <ScrollView>
        <View style={styles.body}>
            <Button title="Press me" onPress={() => start(setImages)} />
            <Gallery imgs={images}/> // Using the state here
        </View>
    </ScrollView>
  );
};

const start = (setImages) => {
  // Create images array here
  setImages(images);
};

export default App;