繁体   English   中英

无法在 React 功能组件中设置 state

[英]Can't set state in a React functional component

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

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。

state 在组件内部维护(声明、设置和使用)。 使用 state 的 function 也需要在组件内部:

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;

基本上,如果在 function 内部声明了一个变量,则其 scope 仅限于该 function 内部。

大卫的回答是正确的,但是如果 function 需要在组件之外,您可以将所需的所有变量作为 arguments 传递,例如

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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