我在更改道具后呈现一些子组件时遇到了一个奇怪的问题。我正在使用 react-select 中的 CreatableInput 组件。如果您想看一下,您可以在这里找到它,也是源代码`react-select lib本身使用内部状态来操纵它的输入值,但是在我的项目中,我需要使用redux存储。在 handleKeyDown 中,我从内部状态获取值并将其发送到我的redux存储,然后连接到存储的父组件接收到更改,但无法设法更新其子组件。当我在输入字段上输入内容并按 ENTER或TAB 时,它实际上会更改存储,但不会立即显示该值,它只会在模糊之后显示。它在内部状态下工作得很好,但在外部状态下却不行。
import React from 'react';
import CreatableSelect from 'react-select/lib/Creatable';
import * as fp from 'lodash/fp';
const components = {
DropdownIndicator: null,
};
const createOption = label => ({
label,
value: label,
});
export default class CreatableInputOnly extends React.Component {
state = {
inputValue: '',
value: {
include: [],
exclude: [],
},
};
handleChange = leftValues => {
this.props.clearInputValues({values: leftValues, filterType: this.props.filterType});
this.setState({
value: {
include: fp.cond([
[fp.isEqual('include'), fp.constant(leftValues)],
[fp.stubTrue, fp.constant([...this.state.value.include])],
])(this.props.filterType),
exclude: fp.cond([
[fp.isEqual('exclude'), fp.constant(leftValues)],
[fp.stubTrue, fp.constant([...this.state.value.exclude])],
])(this.props.filterType),
},
});
};
handleInputChange = inputValue => {
this.setState({inputValue});
};
handleKeyDown = event => {
const {inputValue, value} = this.state;
const addValueToStore = this.props.addValueToStore;
const filterType = this.props.filterType;
if (!inputValue) return;
switch (event.key) {
case 'Enter':
case 'Tab':
this.setState({
inputValue: '',
}, () => {
addValueToStore({values: createOption(inputValue), filterType});
});
event.preventDefault();
}
};
render() {
// eslint-disable-next-line prefer-const
let {inputValue} = this.state;
const {isMulti, isClearable, menuIsOpen, className, classNamePrefix, filterType, inputValues} = this.props;
const allValues = fp.cond([
[fp.isEqual('include'), fp.constant(inputValues.includeUrls)],
[fp.isEqual('exclude'), fp.constant(inputValues.excludeUrls)],
[fp.stubTrue, fp.constant([])],
])(filterType);
console.log(inputValues.includeUrls, '<<<<<<<<<>>>>>>>>>>>>>>>>');
return (
<CreatableSelect
components={components}
inputValue={inputValue}
isClearable={isClearable}
isMulti={isMulti}
menuIsOpen={menuIsOpen}
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder=""
value={allValues}
className={className}
classNamePrefix={classNamePrefix}
/>
);
}
}