代码之家  ›  专栏  ›  技术社区  ›  Sooraj

状态更新后,渲染函数不会更新视图

  •  2
  • Sooraj  · 技术社区  · 7 年前

    constructor(props){
        super(props);
        this.renderConversations = this.renderConversations.bind(this);
        this.startConversation = this.startConversation.bind(this);
        this.state = {
          conversationArray: []
        }
    } 
    

    在函数中 startConversation

    startConversation(conversationObject) {
        let currentResponse = conversationObject["responses"];
        let thisResponse = currentResponse[Math.floor(Math.random() * currentResponse.length)];
    
        this.state.conversationArray.push(thisResponse);
        this.renderConversations();
    
    }
    

    在函数中 renderConversations

    renderConversations(){
        let conversationContent = this.state.conversationArray.map((conv, i) => {
          return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}><Text style= {globalStyle.conversationText}>{ conv }</Text></View>                            
        })
        return conversationContent
    }
    

    {this.renderConversations()} . 现在 但是每次我更新状态变量时,组件都没有更新,我做错了什么?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Mayank Shukla    7 年前

    根据 DOC :

    不变的


    您以错误的方式更新状态,“永远不要直接改变状态值,始终使用 setState 设置状态

    this.setState(prevState => ({
         conversationArray: [...prevState.conversationArray, thisResponse]
    }))
    

    另一个问题是 设置状态为异步 ,我们不能期望更新状态值正好在setState之后,因此请使用的回调方法 然后打电话 renderConversations

    这样地:

    this.setState(prevState => ({...}), () => this.renderConversations())
    

    阅读此答案了解更多有关 async behaviour of setState

    渲染转换 从渲染。