如何使用MaterialUI和Redux将TextField更改为状态?

时间:2017-12-05 14:09:33

标签: reactjs redux react-redux material-ui

使用React / Redux和MaterialUI我设置了一个组件,需要根据您输入的地址检查您的位置或获取lat / lng。

当点击按钮时,我想要地址,输入要在网络服务上检查的TextField。

但是我似乎无法使用按钮将TextField的值传递给webservice。

所以我试着在道具(状态)中立即设置值。 这有效,但我确实收到错误:

  

警告:组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控制切换到受控制(反之亦然)。

此代码如下:



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)
&#13;
&#13;
&#13;

因为我不想要任何错误,所以我也考虑改变位置地址的状态。 所以我创建了一个新的动作setLocationAddress,它应该转到reducer并改变地址的状态,但这对于每次更改都是愚蠢的,因为值已经存在......不需要改变它。

因此我使用表格来做到这一点:

&#13;
&#13;
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>
    );
}
&#13;
&#13;
&#13; 但又是这个唠叨的消息:

  

警告:组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控制切换到受控制(或反之亦然)

那我该怎么做? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

请参阅TextField demo中受控组件的代码。在代码中,onChange prop从状态中拉出,location设置为更新状态的函数。

你其实非常接近。您已将状态映射到value={location.address}道具并且已设置onChange,但this.keepVal已分配给尝试更新道具的keepVal,这是不行的。< / p>

由于您使用的是Redux,因此您需要在state.location.address中发送一个将event.target.value更新为value的操作。这将确保从状态填充组件onChange,并且从已触发的storage <- rnorm(n=20, mean=1, sd=0.4)+N 事件更改将更新商店。