单击编辑按钮

时间:2018-12-11 07:52:11

标签: reactjs react-native

我现在有这三个状态。当我要编辑地址时,不会立即保存。当再次从movit驱动程序页面返回到个人详细信息页面时,它将显示编辑后的输入。

这是movit驱动程序页面 This is the movit driver page

这是个人详细信息 This is the personal details

这是编辑页面 This is the edit page

异步存储可能存在一些问题,当从驱动程序页面返回时,异步存储会显示编辑后的输入。

**Address.js**
  constructor(props) {
    super(props)
    this.state = {
      address: '',
      userToken: null
    }
  }
  
  async componentWillMount() {
    try {
      let value = await AsyncStorage.getItem('userData')
      let userDetails = JSON.parse(value)
      console.log('userDetails 2: ', userDetails)
      if (userDetails !== null) {
        this.setState({
          address: userDetails.address,
          userToken: userDetails.token
        })
      }
      } catch (error) {
        console.log(error)
    }
  }

  saveAddressEdit = (fieldName, fieldValue) => {
    AsyncStorage.setItem(fieldName, fieldValue)
  
    let {userToken} = this.state
  
    var formData = new FormData()
    formData.append(fieldName, fieldValue)
  
    fetch('MyURL', {
      method: 'POST',
      headers: {
        'X-API-KEY': 'myApiKey',
        'Authorization': userToken
      },
      body: formData
    }).then(function (response) {
       console.log(response)
       let data = JSON.parse(response._bodyText)
       Alert.alert(data.message)
    })
    .catch((error) => {
      console.log(error)
    })
    .done()
  }

  render() {
    const {address} = this.state

    return (
      <Container>
        <Content style={{marginHorizontal:20}}>
          <Item style={{marginVertical:40}}>
            <Input placeholder=" Type your Address:" 
              onChangeText={(address) => this.setState({address})}
              value={address}
            />
          </Item>
           <Button full danger  onPress={()=>this.saveAddressEdit('address', address)} style={{backgroundColor:'#ff0000'}}>
                <Text style={{color: '#ffffff'}}>Update Address</Text>
              </Button>
        </Content>
      </Container>
    );
  }
}

这是用于编辑的 address.js 代码。我需要的解决方案就像我想立即显示已编辑的输入。预先感谢。

1 个答案:

答案 0 :(得分:0)

单击按钮时您没有通过状态。将onPress函数调用更改为

onPress={()=>this.saveAddressEdit('address', this.state.address)}

另外,更改TextInput值

value = {this.state.address}

不要在onTextChange回调中使用与常量相同的名称

所以最终的渲染功能是

render() {

    return (
      <Container>
        <Content style={{marginHorizontal:20}}>
          <Item style={{marginVertical:40}}>
            <Input placeholder=" Type your Address:" 
              onChangeText={(address) => this.setState({address:address})}
              value={this.state.address}
            />
          </Item>
           <Button full danger  onPress={()=>this.saveAddressEdit('address', this.state.address)} style={{backgroundColor:'#ff0000'}}>
                <Text style={{color: '#ffffff'}}>Update Address</Text>
              </Button>
        </Content>
      </Container>
    );
  }