componentWillReceiveProps中的状态何时可用?

时间:2016-03-11 22:24:14

标签: reactjs

我构建了一个文本输入组件,允许用户在文本框中输入数字。如果用户输入有效数字,该组件将调用它onChange prop,并将其状态设置为他们输入的字符串。这样,如果用户输入“ - ”或“。”。组件本身可以保留“ - ”或“。”当用户输入其余的号码时,在文本框中。

当他们最终输入有效数字时,会对其进行解析并传递给onChange道具。然后父进程设置自己的内部状态,并将解析后的数字传递回value prop。

父母也可能因为用户输入以外的原因而在value道具中发送新号码,因此我需要实施componentWillReceiveProps以在收到新值时覆盖该州。< / p>

这会导致一个新问题:当用户输入“0”时在输入框中,它成功解析为数字0,通过onChange道具传递给父,然后通过value道具传回给孩子。然后组件在其上调用toString(),这将导致字符串“0”,其覆盖“0”。并且无法输入带小数的数字。

要解决该问题,组件首先检查value prop中传递的值是否等于状态中的字符串,然后解析它(基本上,如果规范化后两个值相等)并且它们是,它不会覆盖状态中的值,因此显示给用户的字符串将保持不变。

但是,在componentWillReceiveProps内,状态与旧版本的状态相同,并不反映用户键入的新字符。操作似乎按此顺序发生:

  1. 用户输入字符。
  2. 调用字符回调。输入是有效数字。
  3. 组件调用setState来更新表示输入字符串的内部状态。
  4. 组件调用onChange prop将新号码传递给父级。
  5. 父级设置自己的状态。
  6. Parent将自己的状态传递回value prop中的组件(作为数字)。
  7. componentWillReceiveProps被称为
  8. 应用来自组件的待处理状态更改。
  9. 问题是由#7之前发生的#7引起的(可能是我没有挖到React源来验证这一点)。我通过在用户键入字符时直接在回调中修改this.state以及使用具有相同值的setState来解决此问题,但我知道直接修改this.state应该如果可能的话,应该避免。

    所以我的问题是:我可以在不直接修改this.state的情况下解决这个问题吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

编辑:我刚才意识到我完全错过了你的问题。 :|

你可以这样做:

public class User {
//Instance Variables
private String name;
private String email;
private Playlist favoriteSongs;

//Constructors
public User(String name, String email, Playlist favoriteSongs){
    this.name = name;
    this.email = email;
    Songs[] songs = this.favoriteSongs.getSongList();
}
public User(String name, String email){
    this.name = name;
    this.email = email;
}
//Setters
public void setPlayList(Playlist list){
    this.favoriteSongs = list;
}
//Get song title by inputting the position in the playlist array
public String getSongTitle(int pos){
    if (pos == this.favoriteSongs.getSongList())
        return Playlist.length[pos];
}
//Add new song to the playlist
public int addSong(String title, String filePath, String artist){
    for(int i=0; i<this.Playlist.length; i++) {
        if ((this.songList[i].getTitle().getArtist() == addSong(i))) // or what ever you want to compare
            return 0;
          }
          // if you do not found any thing
        return -1;
        }
}
// Counts how many songs with the same artist
public int artistSongCount(String artist){
    int count = 0;
    for (int i=0; i < Playlist.numOfSongs.length; i++)
        if (this.favoriteSongs[i].getArtist() == artist)
            count++;

    return count;
}
}
//Print out details of user
public String toString(){
    String userOutput = "";
    userOutput += "Name: "+ name;
    userOutput += "Email: "+ email;
    return userOutput;
}
相关问题