【问题标题】:React Native - Why is this state object empty in function?React Native - 为什么这个状态对象在函数中是空的?
【发布时间】:2018-08-05 10:36:21
【问题描述】:

我有这个 React-Native 组件,它在列表中呈现一个图片库。因此,该父列表上的每个项目都会调用一次。 它接收两个道具,具有项目标题的“etiqueta”和“画廊”,这是一个画廊数组(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.state = 这样的状态,您不会调用重新渲染。使用函数this.setState({ ... }),因为这将触发所需的生命周期运动
  • 不要在构造函数之外分配给state,而是使用setState
  • 另外,小建议:在像​​ etiqueta_id = this.props.etiqueta.id ; 这样的行中,不要忘记前面的 const(或 let),否则你最终会创建一堆全局变量以后可能会出现问题。
  • @SterlingArcher 和 SrThompson 对此表示感谢,这是有道理的。我改变了,但一切看起来都一样。 (我会更新代码)
  • @kingdaro 谢谢,我来自 php,有时忘记做出正确的声明

标签: javascript reactjs react-native


【解决方案1】:

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

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

【讨论】:

  • 完美!这成功了!太感谢了! example2() 中的 console.log 一直在思考,这种行为正常吗?
  • 不太确定那个:/为了简单起见,我建议使用普通函数而不是getter
  • 我会试试的,我现在正在使用他们 github 中的示例。再次感谢您!
  • @kilinkis get example() 将在您访问this.example2 时被调用,因此每当您的EtiquetaDetail 组件触发重新渲染时它就会触发。见this question for details on get
猜你喜欢
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 2023-03-02
  • 2020-07-01
  • 1970-01-01
  • 2017-10-22
  • 2015-11-18
  • 2020-11-13
相关资源
最近更新 更多