violet0sea / note

can not open gist, so write here
0 stars 0 forks source link

React #11

Open violet0sea opened 6 years ago

violet0sea commented 6 years ago

@v16.0 1.render方法可以返回不同于以往的数组元素和字符串 返回数组元素时需要添加key值 render() { return [

  • First item
  • ,
  • Second item
  • ,
  • Third item
  • , ]; } 字符串 render() { return "the string you need here"; } 2.更好的错误处理 之前组件在渲染时遇到错误会破坏状态,导致页面无法渲染;新的错误处理在对待错误时只会将当前组件从根元素中卸载 使用componentDidCatch 可以处理错误 3.ReactDOM新增createPortal方法 render() { return ReactDOM.createPortal( this.props.children, domNode ); } react 会把children渲染到domNode节点里,有时候可以直接将当前的dom渲染到一个不同位置的dom节点里,其次之前的方法每次都会产生一个包裹的div,导致dom树的深度增加,采用这个方法可以减少一个包裹元素,嵌套层级多的话,效果会更棒。 4.更好的服务端渲染 5未知dom属性的支持,以前会直接忽略,现在会保留 为什么会保留 a.可以支持浏览器的自己的非标准属性,使用新的dom apis ,以及和第三方库的交互 b.因为要确定是不是标准属性,React会维护一个白名单,dom属性更新就需要同步白名单,去除掉以后还可以减少打包大小
    6.包的大小减少 5.3kb(from 20.7kb) 7.MIT lisenced 8.新的核心结构 使用Fiber 使用异步渲染,react可以更好的应对阻塞主线程的问题
    violet0sea commented 6 years ago

    @v16.3(.0-alpha)

    1.context Api 之前一直存在 用于父组件向深层次的子组件传递数据 之前一直不使用是因为api可能会在将来发生改变 可以在不使用redux和mobx的情况下管理简单的状态 使用新的createContext方法返回两个组件,Provider和Consumer

    import { createContext } from "react"; const CustomContext = createContext({ //data here 默认的数据 如果在Provider里面没有指定的话就使用当前数据 name: 'cc ' });

    如何使用,Redux的小翻版, provider应该是外层用于包装数据的 render() { <CustomContext.Provider value={{name: 'hai'}}>

    <Main />
    <Footer />

    </CustomContext.Provider> }

    consumer 是内部组件使用数据的 const Header = () => (

    {context => { return (
    {context.name}
    ) }}
    ) 如何更新,这种类似于prop向下传递,所以需要在Provider里面改变数据,然后Consumer里面会自动更新。 2.新的生命周期方法 首先是弃用: componentWillMount componentWillUpdate componentWillReceiveProps 上述方法会在17.0里面完全弃用 新的方法 用来代替componentWillReceiveProps, static方法里面不可以适应this,那么如何使用this.setState???? 如果需要改变的就使用 return方法返回需要变更的state static getDerivedStateFromProps 3.严格模式 使用严格模式带来更好的体验,一些将被移出的方法护在控制台报错 import { StrictMode } from "react"; return ( ) 4.异步模式 5.新的devtool
    violet0sea commented 6 years ago

    React key point:

    make React develop gracefully

    1. Stateless function
    2. JSX spread attributes
    3. Destructuring arguments
    4. Conditional rendering
    5. Children types (string, array, function) string is normal way array means list render function means render callbacks, which is a magic
    6. Children pass-through
    7. Proxy component
    8. Style component const PrimaryBtn = props => <Btn {...props} primary />

    const Btn = ({className, primary, ...props}) => <Button type="button" className={classnames( "btn", primary && "btn-primary", className )} {...props} /> material-ui里的primary 和 secondary控制按钮样式的实现应该也是同理, class控制样式 样式分离 也可以使用style控制 逊色许多 内嵌的样式让显示变得复杂多变

    1. Event Switch
    2. Layout component
    3. Container component fetch data and has lifecycle
    4. High-order component an truly example: ` const Greeting = ({name}) => { if(!name) { return
      Connecting...
      ; } return
      Hi {name!}
      ; }

    const Connect = ComposedComponent => class extends Component { constructor() { super(); this.state = { name: '' }; }

        componentDidMount() {
            this.setState({
                name: 'Lina'
            });
        }
    
        render() {
            return (
                <ComposedComponent
                    {...this.props}
                    name={this.state.name}
                />
            );
        }
    }

    const ConnectedMyComponent = Connect(Greeting);` Connect accept a compont and return a new wrapped component,which can receive new props to change the behavior

    1. State hoisting: passing a callback from parent to children
    2. Controlled input
    violet0sea commented 6 years ago

    关于props传递数据的认知: props传递数据一般情况下可以传js的基本数据类型, 其次可以传递回调函数,主要用于状态提升后的数据更新同步 还有就是可以传递组件

    violet0sea commented 6 years ago

    controlled/uncontrolled component most time use controlled component,you should use state and handler to update value when using uncontrolled component, you can use ref to access the value

    violet0sea commented 4 years ago

    问题: hooks写的组件类似一个封闭的生态系统,状态如何传递出去?原本想着从外部拿到的状态仅作为初始化,传递通过props回调函数实现,但是存在一个问题,回调函数怎么触发?业务场景下是hooks组件平级的下一步组件触发,两个兄弟组件之间传递数据,传统的方法是状态提升,但是因为过于抽象的缘故,这个方法无法实现;另一个想法是组件下沉,让同级组件下沉到hooks组件内部触发事件的时候获取内部状态并传递到上一层

    // 父组件
    class MainComp extends Component {
      handleData = data => {
        // todo handle data
        console.log(data);
      };
      render() {
        return (
          <div>
            <HooksComp
              render={sharedState => <FooterButtonGroup sharedState={sharedState} onClick={handleData} />}
            ></HooksComp>
          </div>
        );
      }
    }
    
    // 底部控制步骤的按钮
    class FooterButtonGroup extends Component {
      handleClick = () => {
        const { onClick, sharedState } = this.state;
        onClick(sharedState);
      };
      render() {
        <div>
          <button>prev</button>
          <button onClick={this.handleClick}>next</button>
        </div>;
      }
    }
    
    // hook组件
    function HooksComp(props) {
      const [state, setState] = useState({ a: 1 });
      const { render } = props;
      return (
        <div>
          <p>{state.a}</p>
          <p>-----分割线-----</p>
          {render(state)}
        </div>
      );
    }
    

    另一种方式

    在HooksComp组件里使用useEffect方法,在里面调用从父组件传递的回调函数,并把需要的数据作为参数传递出去

    class MainComp extends Component {
      handleTransferData = data => {
        // todo handle data
        console.log(data);
      };
      render() {
        return (
          <div>
            <HooksComp onTransferData={this.handleTransferData}></HooksComp>
          </div>
        );
      }
    }
    
    function HooksComp(props) {
      const [state, setState] = useState({ a: 1 });
      const { handleTransferData } = props;
    
      useEffect({
        if (typeof handleTransferData === 'function') {
          const {a,b,c, ...rest} = state;
          handleTransferData({
            a,
            b,
          })
        }
      }, [state.a, state.b]);
    
      return (
        <div>
          <p>{state.a}</p>
          <p>-----分割线-----</p>
          {render(state)}
        </div>
      );
    }