首页 > 解决方案 > 使用 vs 不使用构造函数设置上下文状态

问题描述

当我尝试在没有构造函数的情况下初始化我的状态时,我遇到了函数未绑定到状态的问题。尽管这样的教程在没有构造函数的情况下直接初始化状态,但执行以下操作不起作用。

这不会将功能传递给消费者:

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>  
        );
    };
}

我不确定为什么教程指定第一种方法。

标签: reactjsreact-context

解决方案


您需要在状态之前定义函数:

class App extends React.Component {
  resetForm = () => {
    console.log('reset form');
  };
  state = {
    resetForm: this.resetForm,
  };

  render() {
    this.state.resetForm();
    return 'hi';
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

这看起来像一个 xy 问题,不知道为什么需要将类方法添加到 state。


推荐阅读