反应本机TypeError:_this.setState不是一个函数

时间:2020-03-18 03:34:30

标签: react-native

_this.setstate未在占位符值更改时定义

这是代码。组件

    import React from 'react'; 
    import {SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, 
    TextInput, Button } from 'react-native';
    import { Header, LearnMoreLinks, Colors, DebugInstructions, 
    ReloadInstructions} from 'react-native/Libraries/NewAppScreen';

    const App: () => React$Node = () => {   
       state = {
        placeName: 'dd',
        places: []   
      }   

      placeSubmitHandler = () => {
        if(this.state.placeName.trim() === ''){
          return
        }
        this.setState(preState => {
          return {
            places: preState.places.concat(preState.placeName)
          }
        })
      }   

     placeNameChangeHandler = val => {
        this.setState({
          placeName: val
        })}   

    const placesOutput = this.state.places.map(place => (
        <Text>{place}</Text>
    ))

   return (  
     <View style= {styles.containter}>
        <View style={styles.inputContainer}> 
            <TextInput 
               onChangeText={this.placeNameChangeHandler}  
               value={this.state.placeName} 
               style={styles.placeInput}
               placeholder="input here " 
            />
            <Button onPress={this.placeSubmitHandler} title="Add"/>
        </View>
        <View>
           {placesOutput}
        </View>   
     </View>
    )}

更新(可能的解决方案)

this在功能组件中不可用,因为这仅在类组件中可用 所以不要在功能组件中使用

`

1 个答案:

答案 0 :(得分:0)

这是函数组件,而不是类组件,应该使用useState() 或将其转换为类组件 试试这个`

import React,{useState} from 'react';
import {
     SafeAreaView,
     StyleSheet,
     ScrollView,
     View,
     Text,
     StatusBar,
     TextInput,
     Button
} from 'react-native';

import {
     Header,
     LearnMoreLinks,
     Colors,
     DebugInstructions,
     ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';


const App = ReactNode => {
    const [state, setState] = useState({
         placeName: 'dd',
         places: []
    })

     placeSubmitHandler = () => {
          if (state.placeName.trim() === '') {
               return
          }
          setState(preState => {
               return ({
                    places: preState.places.concat(preState.placeName)
               });
          })
     }
     placeNameChangeHandler = val => {
          setState({
               placeName: val
          })
     }
     const placesOutput = state.places.map(place => ({
          place
     }))
      return ({
          placesOutput
     })
}`