setState({}) не меняет мое логическое значение В ответном нативном приложении

Я пытаюсь показать/скрыть свое поле ввода в React Native, во-первых, я установил свой showFilters true в состоянии, а в своей функции я установил для него значение false... вот так...

hide(){
        console.log("hello");
        this.setState({showFilters: false}); 
      }

вот мой this.state ...

constructor() {

        super();

        this.state = {
            showFilters:true,
            radioButtons: [
            {
              label: 'Freelancer',
              value: 'freelancer',
              checked: true,
              color: '#323232',
              disabled: false,
              onPress: this.hide(),
              size: 11

            },

        {
          label: 'Jobs',
          value: 'jobs',
          checked: false,
          color: '#323232',
          disabled: false,
          size: 11

        },
        {
          label: 'Employer',
          value: 'employer',
          checked: false,
          color: '#323232',
          disabled: false,           
          size: 11   
        } ]

Я хочу скрыть свой макет при нажатии переключателя...

{ this.state.showFilters   ?
                <TextInput style={{fontSize:17 , height:45}}  editable = {true} placeholder="Hello"></TextInput> : null
            }

терминал показывает приветственное сообщение, но не меняет состояние.. показывает предупреждение...

Warning: Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};`

вот код радиокнопки

render(){
        let selectedItem = this.state.radioButtons.find(e => e.checked == true);
        selectedItem = selectedItem ? selectedItem.value : this.state.radioButtons[0].value;
        return(
            <View style={styles.container}>
            <Header style ={{shadowRadius: 0,shadowOffset: {height: 0,},}}
            backgroundColor="#ff5851"
            androidStatusBarColor="#ff5851"
            leftComponent={{ icon: 'menu', color: '#fff' }}
            centerComponent={{ text: 'Start Your Search', style: { color: '#fff',fontWeight:'500', fontSize:20 , width:'100%',fontSize:20, paddingTop:9 ,display:'flex', flexDirection:'column', alignItems:'center'  , justifyContent:'center' , height:40 , borderRadius:20 , alignSelf:'center' , textAlign:'center'  } }}
              />
            <ScrollView>
            <Text style={{fontWeight: '600' , marginBottom:10 , color:'#323232' ,fontWeight:'500', fontSize:20 , marginLeft:10 , marginTop:10 , marginBottom:15 , marginTop:15 }}>Narrow Your Search</Text>
            <View style={{flexDirection:'column' , backgroundColor:'#fff' , paddingLeft:10}}>
            <View style={{borderBottomColor: '#dddddd', borderBottomWidth: 0.6 , marginLeft:-10  , marginBottom:10}}/>
            <Text style={{ marginBottom:10 }}>Narrow Your Search</Text>
            <RadioGroup style={{marginBottom:10 , flexDirection:'row'}}
            color='#ff5851'
            labelStyle={{ fontSize: 14, }}
            radioButtons={this.state.radioButtons}
            onPress={radioButtons => this.setState({ radioButtons })}
            style={{ paddingTop: 20 }}
            />

person S.Hashmi    schedule 21.06.2019    source источник
comment
Пожалуйста, покажите код радиокнопки.   -  person firats    schedule 21.06.2019
comment
@firats я отредактировал свой код   -  person S.Hashmi    schedule 21.06.2019
comment
попробуйте с this.showFilters вне constuctor(){ super() this.statte = {} this.showFilters = false }   -  person AddWeb Solution Pvt Ltd    schedule 21.06.2019
comment
Пожалуйста, объясните @AddWebSolutionPvtLtd, я не понимаю вашу точку зрения   -  person S.Hashmi    schedule 21.06.2019
comment
Не позволять мне использовать его за пределами штата @AddWebSolutionPvtLtd   -  person S.Hashmi    schedule 21.06.2019


Ответы (4)


Сначала избавьтесь от onPress: this.hide() в своем конструкторе. Как это:

super();
        this.state = {
          showFilters:true,
          data: [
          {
            label: 'Freelancer',
            value: 'freelancer',
            checked: true,
            color: '#323232',
            disabled: false,
            size: 11

          },

          {
            label: 'Jobs',
            value: 'jobs',
            checked: false,
            color: '#323232',
            disabled: false,
            size: 11

          },
          {
            label: 'Employer',
            value: 'employer',
            checked: false,
            color: '#323232',
            disabled: false,           
            size: 11   
          } ],
        };

Затем напишите функцию onPress вместо функции скрытия

onPress = data => {
  let selectedButton = data.find(e => e.selected == true);
  selectedButton = selectedButton ? selectedButton.value : 
     this.state.data[0].label;

  if (selectedButton === 'freelancer') {
    this.setState({ data, showFilters: false });
  } else {
    this.setState({ data, showFilters: true });
  }
}

Наконец, в вашей функции рендеринга попробуйте следующее:

<RadioGroup style={{marginBottom:10 , flexDirection:'row'}}
        color='#ff5851'
        labelStyle={{ fontSize: 14, }}
        radioButtons={this.state.data}
        onPress={this.onPress}
        style={{ paddingTop: 20 }}
/>

Код работает на моей машине. Когда вы нажимаете радиокнопку фрилансера, значение showfilter меняется на false.

Просто попробуйте.

person firats    schedule 21.06.2019

Измените onPress: this.hide(), на onPress: this.hide. Вы пишете onPress: this.hide(), поэтому вызываете this.hide() в конструкторе.

person Giang Le    schedule 21.06.2019
comment
Привет, попробуйте один раз, передав реквизиты в конструкторе (реквизиты) { super (реквизиты); - person Vyas Reddy; 21.06.2019

С.Хасми

constructor() {

        super();

        this.state = {
            radioButtons: [
            {
              label: 'Freelancer',
              value: 'freelancer',
              checked: true,
              color: '#323232',
              disabled: false,
              onPress: this.hide(),
              size: 11

            },
            // your code ......
           ]
         }
    this.showFilters = true
   }

hide(){
        this.showFilters =  false
      }

и макет, как

{ this.showFilters   ?
                <TextInput style={{fontSize:17 , height:45}}  editable = {true} placeholder="Hello"></TextInput> : null
            }

попробуйте с этим.showFilters

Благодарность

person AddWeb Solution Pvt Ltd    schedule 21.06.2019

Вы можете вызвать setState с обратным вызовом и передать предыдущее состояние:

setState(prevState => {
   showfilter: !prevState.showFilters
})
person Claeusdev    schedule 21.06.2019