react开发订票网站

react子组件接收父组件的参数传递,并且限制约束? 

import React from 'react';
import PropTypes from 'prop-types';
import './Header.css';

export default function Header(props) {
    const {
        onBack,
        title,
    } = props;

    return (
        

{ title }

); } Header.propTypes = { onBack: PropTypes.func.isRequired, title: PropTypes.string.isRequired, };

redux如何使用?

一、 安装react-redux, 在index.js中导入Provider,并且创建store文件,用Provider包括起来

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import 'normalize.css/normalize.css';

import store from './store';
import './index.css';
import App from './App.jsx';
ReactDOM.render(
      
        
      ,
    document.getElementById('root')
);


二、store文件夹中的文件

1、整理reducers

reducers.js
写法就是导入actions中的常量,判断,更改state

import {
  ACTION_SET_FROM,
  ACTION_SET_TO,
 
} from './actions';

export default {
  from(state = '北京', action) {
    const { type, payload } = action;
    switch(type) {
      case ACTION_SET_FROM:
        return payload;
      default:
    }

    return state;
  },
  to(state = '上海', action) {
    const { type, payload } = action;
    switch(type) {
      case ACTION_SET_TO:
        return payload;
      default:
    }

    return state;
  },  
};

2、actions.js,就是一堆常量
export const ACTION_SET_FROM = 'SET_FROM';
export const ACTION_SET_TO = 'SET_TO';
export function setFrom(from) { 同步的
  return {
    type: ACTION_SET_FROM,
    payload: from,
  };
}
export function toggleHighSpeed() { 异步的
  return (dispatch, getState) => {
    const { highSpeed } = getState();
    dispatch({
      type: ACTION_SET_HIGH_SPEED,
      payload: !highSpeed,
    });
  };
}





三、createStore创建对象,三个参数,第一个将reducers整合起来,第二个默认值,第三个中间件


import { createStore, combineReducers, applyMiddleware } from "redux";

import reducers from './reducers';
import thunk from 'redux-thunk';

export default createStore(
  combineReducers(reducers),
  {
    from: '北京',
    to: '上海',
    isCitySelectorVisible: false,
    currentSelectingLeftCity: false,
    cityData: null,
    isLoadingCityData: false,
    isDateSelectorVisible: false,
    departDate: Date.now(),
    highSpeed: false,
  },
  applyMiddleware(thunk)
)


四、以上步骤完成,就可以使用了
1、组件中引入
import { connect } from 'react-redux';

并且connect,包裹组件,两个方法

export default connect(
  function mapStateToProps(state) {
      return state
  },
  function mapDispatchToProps(dispatch) {
      return { dispatch }
  }
)(App)


这样组件中就可以通过props得到redux中的值和方法
function App(props) {
  const {
    from,
    to,
    dispatch
    isCitySelectorVisible
  } = props;
}

2、如何修改redux中的值
dispatch()传递一个actions方法,就可以直接修改state中的值了

如何批量传递多个actions, 从

import { bindActionCreators } from 'redux';
const cbs = useMemo(() => {
    return bindActionCreators({
      exchangeFromTo,
      showCitySelector,
    }, dispatch);
  }, []);

 

你可能感兴趣的:(React,面试题,react.js,javascript,前端)