【问题标题】:Setting context state with vs without constructor在没有构造函数的情况下使用 vs 设置上下文状态
【发布时间】: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


【解决方案1】:

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

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>

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

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2017-09-18
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2011-11-03
    • 1970-01-01
    • 2013-12-22
    相关资源
    最近更新 更多