React Native:通过安装的非null值进行映射

时间:2018-09-07 12:43:28

标签: reactjs react-native react-redux

以一种安装方式设置组件,然后在我尝试在渲染器中使用该组件时为其分配一个值,对于第一次安装,在将值分配给它之前,该组件为null。但是我需要通过获取的数组进行映射,因此我检查该值是否为null,如果不是,则进行映射..但它似乎使应用程序崩溃了。

class EventCalendar extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
        };

        this.handleGetEvents = this.handleGetEvents.bind(this);
    }

    componentWillMount() {
        this.handleGetEvents();
    }

    handleGetEvents() {
        this.props.getEvents();
    }

    render() {
        const { events } = this.props;
        console.log(events);
        return (
            ...                    {events ?
                                    <ScrollView>
                                        {events.map((event, index) => (
                                            <TouchableOpacity key={index} onPress={() => this.props.navigation.navigate('Event', event)}>
                                                <View style={{ alignItems: 'center', marginLeft: 15, marginRight: 15, paddingRight: 15, borderColor: '#ddd', borderWidth: 1 }}>

                                                    ...
                                                            </View>
                                                        </View>
                                                    </View>
                                                </View>
                                            </TouchableOpacity>
                                        ))}
                                    </ScrollView>
                                    : []
                                };
                            ...
        );
    }
}

3 个答案:

答案 0 :(得分:2)

另一个人说了什么,但为什么不走,不使用三元器呢?

{!!events && events.map ...

而且还没有测试事件的真实性,而是为什么不使用以下方法显式测试它是否是数组:

{Array.isArray(events) && ...

编辑:为用户精心制作:

{Array.isArray(events) &&
  <div>
     {events.map(event => <span>{event.name}</span>)}
  </div>
}

答案 1 :(得分:1)

尝试删除分号和结尾...

所以...

</ScrollView>
: []
};

成为...

</ScrollView>
: []
}

答案 2 :(得分:0)

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
        <div>
          <button onClick={this.focusTextInput}>
            Click to focus Textfield
          </button>
       <br />
       <TextField
         label="My Textfield"
         id="mui-theme-provider-input"
         inputRef={this.textInput} 
       />
     </div>

    );
  }
}