Я новичок в React и встретился с некоторой проблемой с defaultValue на входе или в подходе к настройке состояния. Пример кода, который иллюстрирует это: https://jsfiddle.net/4gxqw5c5/React componentWillMount setState in input no показывает значение состояния
Я ожидаю, что ввод в примере 1-2 будет иметь значение по умолчанию, но он показывает значение заполнителя. Если вы проверите ввод, вы увидите, какое значение было заполнено, но не показано. В примере номер 3 я использую атрибут value и input show real value. Что я делаю неправильно? Пример
Код:
const counter = (state = 0, action) => {
switch(action.type) {
case 'ACTION':
return state + 1;
default:
return state;
}
}
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
componentWillMount() {
this.props.some()
this.props.some()
this.props.some()
this.props.some()
this.props.some()
this.props.some()
this.setState({
textValue: this.props.value
})
}
componentWillReceiveProps(nextProps) {
console.log('props', nextProps)
this.setState({
textValue: this.props.value
})
}
render() {
console.log('render with: ',this.state.textValue)
return (
<div>
<b>1.</b> Bootstrap defaultValue: <br/>
<ReactBootstrap.FormControl
name="text"
placeholder="Enter Text"
maxLength="250"
defaultValue={this.state.textValue}
required
/> <hr />
<b>2.</b> Input defaultValue: <br/>
<input type="text" defaultValue={this.state.textValue} /> <hr />
<b>3.</b> Input value: <br/>
<input type="text" value={this.state.textValue} />
</div>
);
}
}
const {createStore} = Redux;
const store = createStore(counter); // bind reducer
const render =() => {
ReactDOM.render(
<Counter
value={store.getState()}
some={() => {
setTimeout(() => store.dispatch({type: 'ACTION'}), 100)
}} />,
document.getElementById('root')
);
};
store.subscribe(render);
render(); // inital render
Вы можете прочитать этот пост тоже: http://stackoverflow.com/a/30148963/1741027 – slorenzo
@SebastianLorenzo благодарит! – rimlin