2016-11-29 92 views
-1

我正在嘗試編輯和更新React中的一些文本。我正在嘗試使用提示符,但我不確定這是否正確。當我console.log this.state.newText沒有任何顯示。有更好的方法去更新文本?我在我的HTML中使用表格,因此在其中使用輸入會導致錯誤。謝謝!在React中編輯文本

import React, { Component } from 'react'; 
import {IndexLink} from 'react-router'; 
import Item from '../styles/LinkItem.css'; 

class LinkItem extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     clicks: 0, 
     text: this.props.link, 
     newText: '', 
     editing: false 
    }; 
    } 
} 
editLink() { 
    var newText = prompt('Update your link'); 
    this.setState({ 
    newText: newText, 
    editing: false 
    }); 
    console.log(this.state.newText); 
} 
handleClick() { 
    const clicks = this.state.clicks; 
    this.setState({ 
    clicks: clicks + 1 
    }); 
    localStorage.setItem(`link-${this.props.link}`, JSON.stringify(clicks)); 
} 
render() { 
    return (
     <tr> 
     <td> 
      <IndexLink onClick={this.handleClick.bind(this)} to={{pathname: 'landing/' + this.props.link}}>{this.props.link}</IndexLink> 
     </td> 
     <td>{JSON.parse(localStorage.getItem(`link-${this.props.link}`))}</td> 
     <td><button className="btn btn-default" onClick={this.editLink.bind(this)}>Edit</button></td> 
     <td><button className="btn btn-danger" onClick={this.props.data.deleteLink.bind(null, this.props.index)}>Delete</button></td> 
     </tr> 
); 
} 
} 

export default LinkItem; 

回答

1

this.setState是異步的。 console.log使用回調函數(設置state後執行的函數)。這是正確的方法。 setState允許回調。現在它不打印任何東西,因爲它打印了在構造函數中設置爲空字符串的舊值newText

setState()不會立即改變this.state,但會創建暫掛狀態轉換。調用此方法後訪問this.state可能會返回現有值。

this.setState({ 
    newText: newText, 
    editing: false 
    },function(){ 
    console.log(this.state.newText); 
    }); 
1

如果你想更新它後檢查狀態的值,就需要提到它裏面的setState callback因爲setState需要一些時間來發生變異的狀態,因爲JavaScript是異步的console.log()會變得之前執行狀態發生了變化。這就是setState docs

的setState()不會立即發生變異this.state而是創建一個 掛起狀態轉變。調用 方法後訪問this.state可能會返回現有值。

使用下面的代碼

editLink() { 
    var newText = prompt('Update your link'); 
     this.setState({ 
     newText: newText, 
     editing: false 
     }, function(){ 
     console.log(this.state.newText); 
    }); 
}