gpt4 book ai didi

reactjs - 组件在初始化后正在更改不受控制的 Slider 的默认值状态。具有 Redux 状态的 Material UI slider

转载 作者:行者123 更新时间:2023-12-04 14:31:15 24 4
gpt4 key购买 nike

我正在尝试运行一个 redux 操作,该操作获取一个数据库并将其存储在一个状态变量中。然后我使用这个变量作为 Material UI Slider 的默认值。我正在初始化此默认值(以避免通常可以解决问题的 null),然后在获取完成时使用 useState 设置该值。我无法摆脱警告
组件在初始化后正在更改不受控制的 Slider 的默认值状态。
虽然我的滑块值从未设置为 Null
下面是我的页面代码和 reducer
页:

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);
reducer 代码:
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;
}
};

最佳答案

我通过添加 解决了这个问题 key 组成部分

<Slider
key={`slider-${currentConcurrency}`} /* fixed issue */
defaultValue={currentConcurrency}
step={1}
max={maxConcurrency}
min={1}
marks
valueLabelDisplay={'auto'}
onChangeCommitted={this.handleSliderChange('currentConcurrency')} /* increase render performance */
/>

关于reactjs - 组件在初始化后正在更改不受控制的 Slider 的默认值状态。具有 Redux 状态的 Material UI slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62711040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com