我想将react-md与redux集成在一起,但是我不知道如何触发onAutocomplete
函数。现在,我只想从Action中获取一些硬编码的数据,稍后我将添加一个api调用并将搜索文本作为参数。
这是我要分发的硬编码数据的动作:
export const searchCityAutoComplete = () => {
// no need for text parameter to search at this point
const users = [{
id: '1',
name: 'Robin',
}, {
id: '2',
name: 'Yan',
}]
return {
type: "AUTOCOMPLETE_SEARCH",
payload: users
};
}
这是减速器:
const initState = {
searchResults: [],
}
const sitesReducer = (state = initState, action) => {
switch (action.type) {
case "AUTOCOMPLETE_SEARCH":
state = {
...state,
searchResults: action.payload
}
break;
default:
return state;
}
return state;
}
export default sitesReducer;
这是组件
import React from 'react';
import { connect } from 'react-redux';
import { searchCityAutoComplete } from '../actions/sitesActions';
import Autocomplete from 'react-md/lib/Autocompletes';
const SearchAutocomplete = ({ searchResults, onAutocomplete }) => (
<div >
<div className="md-text-container" style={{ marginTop: "10em" }}>
<Autocomplete
id="test-autocomplete"
label="Autocomplete"
dataLabel="name"
autocompleteWithLabel
placeholder="Search Users"
data={searchResults}
onAutocomplete={(...args) => {
searchCityAutoComplete(args)
console.log(args);
}}
deleteKeys={[
"id",
]}
simplifiedMenu={false}
anchor={{
x: Autocomplete.HorizontalAnchors.CENTER,
y: Autocomplete.VerticalAnchors.TOP
}}
position={Autocomplete.Positions.BOTTOM}
/>
</div>
</div>
);
const mapStateToProps = state => {
console.log(state)
return {
searchResults: state.sitesReducer.searchResults,
}
}
const mapDispatchToProps = dispatch => ({
onAutocomplete: () => { dispatch(searchCityAutoComplete()) }
})
export default connect(mapStateToProps, mapDispatchToProps)(SearchAutocomplete);
您可能已经注意到,onAutocomplete
函数与该组件的作用域不同……所以我想这就是为什么它不被触发的原因。首先,我只需要从操作中获取数据-一旦我在自动完成文本框中键入内容,谢谢。
答案 0 :(得分:2)
来自react-md
docs:
onAutocomplete :当使用鼠标,Enter /空格键, 或触摸。
因此,onAutocomplete
仅在选择建议时被调用。这不是您想要的。您正在寻找的是onChange
道具:
onChange :当自动填充的文本字段值更改时调用的可选功能。
在这里您可以找到一个简单的示例代码:https://codesandbox.io/s/muddy-cdn-l85sp
答案 1 :(得分:0)
您只需将onAutocomplete
动作直接传递到Autocomplete
组件中即可:
const SearchAutocomplete = ({ searchResults, onAutocomplete }) => (
<div>
<div className="md-text-container" style={{ marginTop: "10em" }}>
<Autocomplete
id="test-autocomplete"
label="Autocomplete"
dataLabel="name"
autocompleteWithLabel
placeholder="Search Users"
data={searchResults}
onAutocomplete={onAutocomplete} // Pass the action from props here
deleteKeys={[
"id",
]}
simplifiedMenu={false}
anchor={{
x: Autocomplete.HorizontalAnchors.CENTER,
y: Autocomplete.VerticalAnchors.TOP
}}
position={Autocomplete.Positions.BOTTOM}
/>
</div>
</div>
);
然后在mapDispatchToProps
中,您需要接受自动完成值并对其进行搜索或将其设置为reducer:
const mapDispatchToProps = dispatch => ({
onAutocomplete: (value) => dispatch(searchCityAutoComplete(value))
})
export const searchCityAutoComplete = (value) => {
// do smth with the value
const users = [{
id: '1',
name: 'Robin',
}, {
id: '2',
name: 'Yan',
}]
return {
type: "AUTOCOMPLETE_SEARCH",
payload: users
};
}