我正在使用带有材料ui自动完成字段的redux-form .
我需要做的是:
当页面加载自动完成值为空时 .
当用户开始键入并达到3个字符时,我想调用API,并且我希望将该API的结果显示为自动完成数据源 .
我尝试过的:
我试图不设置dataSource并在seconde尝试我设置dataSource = {}在我得到相同的错误消息的情况下:
失败的道具类型:道具数据源在自动完成中被标记为必需,但其值未定义 . **
Home.js类代码
import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import AutoComplete from 'material-ui/AutoComplete';
import {connect} from 'react-redux';
class Home extends Component {
renderAutoComplete = ({
input,
label,
meta: {touched, error},
children,
...custom
}) => (
<AutoComplete
floatingLabelText={label}
errorText={touched && error}
{...input}
onChange={(event, index, value) => input.onChange(value)}
children={children}
{...custom}
/>
)
render() {
const startDate = new Date();
const {handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div>
<Field name="Origin_1" label="FROM" component={this.renderAutoComplete} dataSource={}/>
</div>
<div>
<button type="submit">
Submit
</button>
</div>
</form>
);
}
}
const LogInForm = reduxForm({
form: 'MaterialUiForm', // a unique identifier for this form
validate
})(Home);
export default connect(mapStateTOProps, {getCity})(LogInForm);
2 回答
从demo和source code comments,您可以看到
dataSourse
属性的值必须是一个数组:所以你可以做到以下几点:
将
dataSource
的初始值设置为空数组当输入值的长度更像3个符号时,进行API调用
在api响应回调时更新
dataSource
属性另请注意,如果您将对象数组用于
dataSourse
的值,则每个对象都需要'text'和'value'个键:或用于映射的其他dataSourceConfig:
AutoComplete有一个名为OnUpdateInput的属性 . 它的工作方式类似于keyup属性 . 函数签名如下: -
function(searchText: string, dataSource: array, params: object) => void
searchText将是您应该传递以进行验证的参数 .创建一个函数并传递一个参数并检查argument.length> = 4 . 例如:
check(query){ if(query>=4){ //call API or pass it to actions and then to the reducer and then API }