javascript - React Native - 为什么这个状态对象在函数中是空的?

标签 javascript reactjs react-native

我有这个 React-Native 组件,它在列表中呈现一个图像库。因此,该父列表中的每个项目都会调用一次。 它接收两个 props,“etiqueta”(具有项目的标题)和“gallery”(画廊数组(javascript 文字))。我知道它应该只接收我们需要渲染的图库,但我无法做到这一点,所以现在,我发送所有图库并在此组件中过滤它们。

问题:当我 console.log ComponentDidMount 中的状态时,一切看起来都很好,state.entries 有需要渲染的图库。但是当我尝试在 get Example2() 中访问它时,它返回一个空数组。我不确定为什么会发生这种情况。

而且,由于某种原因,get Example2() 中的 console.log 在控制台中不断运行。为什么会发生这种情况?

这是我尝试使用的图库:https://github.com/archriss/react-native-snap-carousel

当然感谢您的宝贵时间,希望我说得足够清楚,我是 React 新手。

class EtiquetaDetail extends Component {

  constructor(props) {
    super(props);

    this.state = {
      slider1ActiveSlide: 0,
      slider1Ref: null,
      entries: [],
      isMounted: false
    };
  }

  componentDidMount() {

    let etiqueta_id = this.props.etiqueta.id ;

    if ( this.props.etiqueta ) {

      // select the gallery we need to render
      gallery = this.props.galleries.find(function (obj) {
        return obj.id_gal === etiqueta_id;
      });

      ENTRIES1 = JSON.parse( gallery.data );

      this.setState = {
        slider1ActiveSlide: 0,
        slider1Ref: null,
        entries: ENTRIES1,
        isMounted: true
      };
      console.log(this.state); // this outputs everything as expected

    }

  }

get example2 () {
  console.log(this.state.entries); // returns 0 
    return (
        <View>
            <Carousel
              data={ this.state.entries }
            />
        </View>
    );
}

  render() {

    const etiqueta = this.props;

    const { title } = this.props.etiqueta;

    return (
      <Card>
        <CardSection>
          <View>
            <Text>{title.rendered}</Text>
          </View>
        </CardSection>

        <SafeAreaView>
            <View}>
                <ScrollView>
                    { this.example2 }
                </ScrollView>
            </View>
        </SafeAreaView>

      </Card>
    )
  };

};

最佳答案

当您需要在构造函数之外更新状态时,请使用 this.setState,让 React 知道它需要重新渲染。

this.setState({
  slider1ActiveSlide: 0,
  slider1Ref: null,
  entries: ENTRIES1,
  isMounted: true
})

关于javascript - React Native - 为什么这个状态对象在函数中是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980583/

相关文章:

javascript - Div 动态调整为窗口高度,但在将更多内容添加到 HTML 时失败

基于当前浏览器的宽度和高度的 JavaScript CSS 选择

reactjs - 如何将 react 路由器中的状态传递给组件

javascript - 如何在 react native - flatList 中创建两列之间有空格

javascript - react-native-webview 只有在 react-navigation tabNavigator 中的事件选项卡上时才开始加载

javascript - NightmareJS 从字符串创建页面

javascript - 如何隐藏 URL 中的文件夹/路径并仅保留域

javascript - 创建一个 debounced 函数,在搜索时延迟调用 func

html - getUserMedia API 不适用于 React 中的 iOS Safari

javascript - React Native 中的链接库故障排除