无类反应状态?

时间:2019-12-05 01:24:45

标签: javascript reactjs

我正在尝试使用react-boilerplate构建一个简单的应用程序,容器(基本上是视图)和组件不使用类来创建新组件,而是它们是基本功能。通常,您向类添加构造函数或直接状态,因为没有类,我不知道在何处添加状态定义。香港专业教育学院无处添加构造器或状态定义的地方,您可以在此模式下的此视图中的此处添加简单反应(NO redux)状态列表或构造器吗?

容器示例

/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 */

import React, { useEffect, memo } from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';

import { useInjectReducer } from 'utils/injectReducer';
import { useInjectSaga } from 'utils/injectSaga';
import {
  makeSelectRepos,
  makeSelectLoading,
  makeSelectError,

} from 'containers/App/selectors';
import H2 from 'components/H2';
import ReposList from 'components/ReposList';
import AtPrefix from './AtPrefix';
import CenteredSection from './CenteredSection';
import Form from './Form';
import Input from './Input';
import Section from './Section';
import messages from './messages';
import { loadRepos } from '../App/actions';
import { changeUsername, setHomeVisible } from './actions';
import { makeSelectUsername, makeHomeVisible } from './selectors';
import reducer from './reducer';
import saga from './saga';
import NavBar from './NavBar';
import ButtonLink from './ButtonLink';

const key = 'home';

export function HomePage({
  username,
  loading,
  error,
  repos,
  onSubmitForm,
  onChangeUsername,
  homeVisible,
  makeHomeVisible,
  setHomeVisible
}) {
  useInjectReducer({ key, reducer });
  useInjectSaga({ key, saga });

  useEffect(() => {
    // When initial state username is not null, submit the form to load repos
    if (username && username.trim().length > 0) onSubmitForm();
  }, []);

  const reposListProps = {
    loading,
    error,
    repos,
  };

  return (
    <article>
      <Helmet>
        <title>title</title>
        <meta
          name="description"
          content=""
        />
      </Helmet>
      <NavBar>
        <ButtonLink to="/" onClick={makeHomeVisible}>
          <FormattedMessage {...messages.websites} />
        </ButtonLink>
        <ButtonLink to="/apps" >
          <FormattedMessage {...messages.apps} />
        </ButtonLink>
      </NavBar>
      <div className={`home ${this.state.visible === false ? 'hidden': ''}`}>
        <Section>
          <H2>
            <FormattedMessage {...messages.trymeHeader} />
          </H2>
          <Form onSubmit={onSubmitForm}>
            <label htmlFor="username">
              <FormattedMessage {...messages.trymeMessage} />
              <AtPrefix>
                <FormattedMessage {...messages.trymeAtPrefix} />
              </AtPrefix>
              <Input
                id="username"
                type="text"
                placeholder="mxstbr"
                value={username}
                onChange={onChangeUsername}
              />
            </label>
          </Form>
          <ReposList {...reposListProps} />
        </Section>
      </div>
    </article>
  );
}

HomePage.propTypes = {
  loading: PropTypes.bool,
  homeVisible: PropTypes.bool,
  error: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  repos: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]),
  onSubmitForm: PropTypes.func,
  username: PropTypes.string,
  onChangeUsername: PropTypes.func,
  makeHomeVisible: PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  repos: makeSelectRepos(),
  username: makeSelectUsername(),
  loading: makeSelectLoading(),
  error: makeSelectError(),
  homeVisible: makeHomeVisible(),
});

export function mapDispatchToProps(dispatch) {
  return {
    onChangeUsername: evt => dispatch(changeUsername(evt.target.value)),
    makeHomeVisible: evt => dispatch(setHomeVisible(evt.target.value)),
    onSubmitForm: evt => {
      if (evt !== undefined && evt.preventDefault) evt.preventDefault();
      dispatch(loadRepos());
    },
  };
}

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

export default compose(
  withConnect,
  memo,
)(HomePage);

1 个答案:

答案 0 :(得分:1)

根据React Docs,您可以使用useState钩子将数据保存到状态。没有“状态列表或构造函数”,但是您可以简单地访问传入的道具,并决定将其保存为状态(如果要操纵它们)-如果不坚持使用这些道具。 / p>

Codesandbox Demo

基本示例:

function Child(props) {
  let [name, setName] = useState(props.data.name);

  function updateName () {
    setName('The Dude');
  }
   return (
    <div className="App">
     <h2>{name}</h2>
     <button onClick={updateName}>Update</button>
    </div>
  );
};

function App() {
  let [data, setData] = useState({name: 'dude'});
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Child data={data}/>
    </div>
  );
}