2017-12-05 3 views
1

React/Redux 및 MaterialUI 사용 위치를 확인하거나 입력 한 주소를 기준으로 위도/경도를 알아야하는 구성 요소를 설정했습니다.MaterialUI 및 Redux를 사용하여 TextField 변경 사항을 상태로 설정하는 방법은 무엇입니까?

버튼을 클릭하면 입력 한 주소를 입력하고 싶습니다. 웹 서비스에서 검사 할 TextField.

그러나 버튼을 사용하여 webservice에 TextField 값을 가져올 수 없습니다.

그래서 (국가의) 소품에서 즉시 값을 설정하려고했습니다. 이 작동하지만 오류받을 수 있나요 :

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

이 코드는 다음과 같다 : 나는 또한 변화에보고 오류를 원하지 않기 때문에 그래서

import React, { Component } from 'react'; 
 
import { connect } from 'react-redux'; 
 
import { Field, reduxForm } from 'redux-form' 
 
import TextField from 'material-ui/TextField'; 
 
import IconButton from 'material-ui/IconButton'; 
 
import PlaceIcon from 'material-ui-icons/Place'; 
 
import SearchIcon from 'material-ui-icons/Search'; 
 

 
import { getLocationByAddress, getLocationByLatLng } from '../actions'; 
 

 

 
/** 
 
* Location Search, Lets the user search for his location and coordinates 
 
* @class LocationSearch 
 
* @extends React.Component 
 
*/ 
 
class LocationSearch extends Component { 
 

 
    /** 
 
    * getLocationByLatLng: uses navigator.geolocation to get the current position of the user <br/> 
 
    * then requests the information from a back-end service to retrieve full location data. 
 
    */ 
 
    getLocationByLatLng() { 
 

 
     let options = { 
 
      enableHighAccuracy: true, 
 
      timeout: 5000, 
 
      maximumAge: 0 
 
     }; 
 

 
     navigator.geolocation.getCurrentPosition(function (pos) { 
 
      console.log(pos.coords); 
 

 
     }, function(err){ 
 
      console.warn(`ERROR(${err.code}): ${err.message}`); 
 
     }, options) 
 
    } 
 

 
    /** 
 
    * getLocationByAddress: uses address to request full location data from back-end service 
 
    */ 
 
    getLocationByAddress = (e) => { 
 
     /* 
 
     console.log(e); 
 
     e.preventDefault(); 
 
     */ 
 

 
     this.props.getLocationByAddress(this.props.location.address); 
 
    }; 
 

 
    keepVal = ({target}) => { 
 

 
     this.props.location.address = target.value; 
 

 
    }; 
 

 
    render() { 
 

 
     const { location } = this.props; 
 

 
     return (
 
      <div className={'locationSearch'}> 
 

 
       <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label=""> 
 
        <PlaceIcon fontSize={35} /> 
 
       </IconButton>    
 
        <TextField 
 
         value={location.address} 
 
         placeholder={'Voer uw locatie in'} 
 
         margin={'normal'} 
 
         className={'locationSearch_input'} 
 
         onChange={this.keepVal} 
 
        /> 
 
        <IconButton onClick={this.getLocationByAddress} color="primary" className={'locationSearch_searchBtn'} aria-label=""> 
 
         <SearchIcon fontSize={35} /> 
 
        </IconButton> 
 
      </div> 
 
     ); 
 
    } 
 

 
} 
 

 
function mapStateToProps (state) { 
 
    return { 
 
     location: state.location 
 
    } 
 
} 
 

 
export default connect(mapStateToProps, {getLocationByAddress, getLocationByLatLng})(LocationSearch)

을 위치 주소에 대한 상태. 그래서 새로운 액션 setLocationAddress를 만들었습니다. 주소를 변경하기 만하면 주소가 변경되지만 모든 변경 작업을 바보로 처리해야합니다. 값이 이미 있으므로 변경할 필요가 없습니다.

따라서 나는이 작업을 수행 할 수있는 양식을 사용 :

getLocationByAddress = (e) => { 
 
    e.preventDefault(); 
 
    const { target } = e; 
 
    this.props.getLocationByAddress(target['locationInput'].value); 
 
}; 
 

 
render() { 
 

 
    const { location } = this.props; 
 

 
    return (
 
     <div className={'locationSearch'}> 
 

 
      <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label=""> 
 
       <PlaceIcon fontSize={35} /> 
 
      </IconButton> 
 
      <form onSubmit={this.getLocationByAddress}> 
 
       <TextField 
 
        name={'locationInput'} 
 
        value={location.address} 
 
        placeholder={'Voer uw locatie in'} 
 
        margin={'normal'} 
 
        className={'locationSearch_input'} 
 
       /> 
 
       <IconButton color="primary" className={'locationSearch_searchBtn'} aria-label=""> 
 
        <SearchIcon fontSize={35} /> 
 
       </IconButton> 
 
      </form> 
 
     </div> 
 
    ); 
 
}
그러나 다시 naggy 메시지 : 내가 이렇게 어떻게 그래서

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa)

?를 도움이 될 것입니다.

+0

왜 텍스트 필드 값을 소품에 저장하고 있습니까? 당신은 또한 redux뿐만 아니라 사용하고 있기 때문에 setState – link0047

+0

상태로 저장해야합니까? – BonifatiusK

+1

자체 소품을 업데이트하는 구성 요소는 안티 패턴입니다. 만약 당신이 당신의 주를 redux에 저장하고 있다면 당신은 파견 방법을 사용해야합니다. – link0047

답변

0

에 제어되는 구성 요소에 대한 코드를 참조하십시오. 코드에서 value 소품은 상태에서 가져오고 onChange은 상태를 업데이트하는 기능으로 설정됩니다.

당신은 실제로 아주 가깝습니다. 상태를 location 소품에 매핑했으며 value={location.address}으로 설정했지만 onChange은 소품 업데이트를 시도하는 this.keepVal에 할당됩니다.

Redux를 사용하고 있으므로 keepValstate.location.address이라는 메시지를 event.target.value으로 업데이트해야합니다. 이렇게하면 구성 요소 value이 상태에서 채워지고 해고 된 onChange 이벤트의 변경으로 인해 저장소가 업데이트됩니다.

관련 문제