Moh*_*her 3 reactjs redux material-ui
我正在尝试运行一个 redux 操作,该操作获取一个数据库并将其存储在一个状态变量中。然后我使用这个变量作为 Material UI Slider 的默认值。我正在初始化此默认值(以避免通常可以解决问题的 null),然后在获取完成时使用 useState 设置该值。我无法摆脱警告 A 组件在初始化后正在更改不受控制的 Slider 的默认值状态。虽然我的滑块值从未设置为 Null 下面是我的页面代码和减速器页面:
import React, { useState, useEffect } from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import Slider from '@material-ui/core/Slider';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getSettings } from '../../actions/settingsActions';
const Settings = ({ getSettings, settings }) => {
React.useEffect(() => {
getSettings();
// eslint-disable-next-line
}, []);
const [current, setCurrent] = useState({
ageAtDeath: 50,
});
React.useEffect(() => {
if (settings.ageAtDeath) {
//only loads when settings is not null as set in initial state getSettings() completed!
setCurrent({
ageAtDeath: settings.ageAtDeath,
});
}
}, [settings]);
return (
<Card>
<CardContent>
<Typography color='textSecondary' gutterBottom>
Age at death:
</Typography>
<Slider
defaultValue={current.ageAtDeath}
aria-labelledby='discrete-slider'
valueLabelDisplay='auto'
step={10}
marks
min={10}
max={110}
/>
</CardContent>
</Card>
);
};
Settings.propTypes = {
getSettings: PropTypes.func.isRequired,
settings: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
settings: state.settings.settings,
});
export default connect(mapStateToProps, {
getSettings,
})(Settings);
Run Code Online (Sandbox Code Playgroud)
减速机代码:
import {
GET_SETTINGS,
} from '../actions/Types';
const initialState = {
settings: {ageAtDeath: 0},
};
export default (state = initialState, action) => {
switch (action.type) {
case GET_SETTINGS:
return {
...state,
settings: action.payload,
};
default:
return state;
}
};
Run Code Online (Sandbox Code Playgroud)
Ngu*_*ong 28
\xe2\x9a\xa0\xef\xb8\x8f 您应该使用value属性而不是defaultValue\xe2\x9a\xa0\xef\xb8\x8f
<Slider\n value={current.ageAtDeath} /*defaultValue={current.ageAtDeath}*/\n aria-labelledby='discrete-slider'\n valueLabelDisplay='auto'\n step={10}\n marks\n min={10}\n max={110}\n />\nRun Code Online (Sandbox Code Playgroud)\n
我通过向组件添加密钥解决了这个问题
<Slider
key={`slider-${currentConcurrency}`} /* fixed issue */
defaultValue={currentConcurrency}
step={1}
max={maxConcurrency}
min={1}
marks
valueLabelDisplay={'auto'}
onChangeCommitted={this.handleSliderChange('currentConcurrency')} /* increase render performance */
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4219 次 |
| 最近记录: |