简体   繁体   English

使用 setTimeOut 再次调用 setState 来响应更改状态

[英]React change state with setTimeOut calling setState again

New to react native.新的反应原生。 I want to use state to change a button colour (that I defined in a class component) on a certain condition.我想使用 state 在特定条件下更改按钮颜色(我在类组件中定义的)。 I used setTimeOut and setState and right now the button changes, but only once (from darkgreen to lightgreen).我使用了 setTimeOut 和 setState,现在按钮改变了,但只有一次(从深绿色到浅绿色)。 Tried using setInterval and it did the same.尝试使用 setInterval 并且它做了同样的事情。 I want it to change from dark to light and back to dark again.我希望它从黑暗变为光明,然后再变回黑暗。 But I can't seem to find a way to call setState again.但我似乎找不到再次调用 setState 的方法。 Would like some help, please.想要一些帮助,请。 Thanks a lot, here is the class component:非常感谢,这是类组件:

class Green extends Component {
     constructor(props){
         super(props)
         this.state={}
         this.state.custum={
            backgroundColor: 'darkgreen'
         }

         if (this.props.greenFlash){
            setTimeout(() => {
                this.setState( {
                    custum:{
                        backgroundColor: 'lightgreen'
                    }
                    })
            }, 1000);
        }
     }    
    render() {
        return (
            <View style={[styles.greenB, this.state.custum]}> 
            </View>
        );
      }
    }  
    var styles = StyleSheet.create({
        greenB:{
          padding: 5,
          height: 80,
          width: 80,  
          borderRadius:160,    

        },
    })
export default Green;

try this working example acc to your code expo link :尝试这个工作示例acc到您的代码博览会链接

Code is :代码是:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

class Green extends React.Component {
     constructor(props){
         super(props)
         this.state={
            backgroundColor: 'darkgreen'
         }

     }   

     componentDidMount() {
       setInterval(() => {
         if(this.state.backgroundColor == "darkgreen"){
           this.setState({backgroundColor:'red'})
         } else {
           this.setState({backgroundColor:'darkgreen'})
         }

     },1000)
     }
    render() {
        return (
            <View style={[styles.greenB,{backgroundColor:this.state.backgroundColor}]}> 
            </View>
        );
      }
    }  
    var styles = StyleSheet.create({
        greenB:{
          padding: 5,
          height: 80,
          width: 80,  
          borderRadius:160,    

        },
    })
export default Green;

I would do it like this:我会这样做:

constructor(props) {
     super(props)
     this.state={}
     this.state.custum={
        backgroundColor: 'darkgreen'
     }

     if (this.props.greenFlash){
        this.intervalId = setInterval(() => {
            this.setState(prevState => {
              const bgcolor = (prevState.custum.backgroundColor === 'lightgreen') ? 'darkgreen' : 'lightgreen';
              return {
                custum:{
                    backgroundColor: bgcolor
                 }
                }
            })
        }, 1000);
    }
 } 

A few things to note:需要注意的几点:

A) You're saving this.intervalId so you can call clearInterval(this.intervalId) in your componentWillUnmount . A)您正在保存this.intervalId以便您可以在componentWillUnmount调用clearInterval(this.intervalId) Otherwise your interval will keep on calling long after your component has been destroyed.否则,在您的组件被销毁后,您的时间间隔将继续调用很长时间。

B) you may want to define your interval in componentDidMount instead of the constructor, as that's generally the standard when you're calling this.setState , because this.setState is not available until componentDidMount is called. B)您可能希望在定义你的间隔componentDidMount而不是构造的,因为这通常是当你调用标准this.setState ,因为this.setState直到不可componentDidMount被调用。 However, because the first time it will be called is after 1 second, I'm not going to say it's a huge concern.但是,因为它第一次被调用是在 1 秒之后,所以我不会说这是一个很大的问题。 Just standard practice.只是标准做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM