【发布时间】:2020-05-18 06:55:18
【问题描述】:
当我尝试在没有构造函数的情况下初始化我的状态时,我遇到了函数未绑定到状态的问题。尽管像 this 这样的教程在没有构造函数的情况下直接初始化状态,但执行以下操作不起作用。
这不会将函数传递给消费者:
class NewTownFormContextProvider extends Component {
state = {
towns:[],
name: '',
parish: '',
categories:[],
catList:[],
resetForm: this.resetForm,
updateTown: this.updateTown,
updateParish: this.updateParish,
setCategory: this.setCategory,
submit: this.submit
}
resetForm = ()=>{
this.setState({
name:'',
parish:'',
categories:[]
})
}
updateTown = (e) =>{
this.setState({town: e.target.value});
console.log(this.state.town);
}
updateParish = (e) =>{
this.setState({parish: e.target.value});
console.log(this.state.parish);
}
setCategory = (e) =>{
this.setState({category: e.target.value});
console.log(this.state.category);
}
submit = async (e) => {
e. preventDefault();
this.setState([...this.state.towns, {name: this.state.town, parish: this.state.parish}])
}
}
async componentDidMount(){
let data = await fetch(`${d}/town/get-categories`);
let catList = await data.json();
this.setState({ catList });
}
render(){
return(
<NewTownFormContext.Provider value={{...this.state }}>
{this.props.children}
</NewTownFormContext.Provider>
);
};
}
但这确实:
class NewTownFormContextProvider extends Component {
constructor(props){
super(props);
this.state = {
towns:[],
name: '',
parish: '',
categories:[],
catList:[],
resetForm: this.resetForm,
updateTown: this.updateTown,
updateParish: this.updateParish,
setCategory: this.setCategory,
submit: this.submit
}
}
resetForm = ()=>{
this.setState({
name:'',
parish:'',
categories:[]
})
}
updateTown = (e) =>{
this.setState({town: e.target.value});
console.log(this.state.town);
}
updateParish = (e) =>{
this.setState({parish: e.target.value});
console.log(this.state.parish);
}
setCategory = (e) =>{
this.setState({category: e.target.value});
console.log(this.state.category);
}
submit = async (e) => {
e. preventDefault();
this.setState([...this.state.towns, {name: this.state.town, parish: this.state.parish}])
}
}
async componentDidMount(){
let data = await fetch(`${d}/town/get-categories`);
let catList = await data.json();
this.setState({ catList });
}
render(){
return(
<NewTownFormContext.Provider value={{...this.state }}>
{this.props.children}
</NewTownFormContext.Provider>
);
};
}
我不确定为什么教程指定第一种方法。
【问题讨论】:
-
你能展示你的 webpack 配置吗?
-
我用 create-react-app 创建了这个应用,所以它有点长。
-
在这种情况下它应该支持类属性,我认为@HMR 回答会解决你的问题
-
给出答案后我意识到没有必要向状态添加类方法,不知道为什么你认为你需要这样做。
-
如果你这么说是因为这些大多只是设置数据,我正在使用一些非常具体的函数来设置状态,这将是一个很好的解决方案。就像从一个状态获取内容并使用它来更新其他状态。
标签: reactjs react-context